7

我有这个架构:

var orderSchema = new mongoose.Schema({
  history: [{
    "type": {
      type: String,
      enum: [
        'ORDER_HISTORY_DRIVER_DETAILS',
        'ORDER_HISTORY_LOADING',
        'ORDER_HISTORY_LOCATION',
        'ORDER_HISTORY_UNLOADING'
      ],
      required: true
    },
    date: {
      type: Date
    },
    state: {
      type: String,
      enum: [
        'ORDER_HISTORY_STEP_STATE_COMPLETED',
        'ORDER_HISTORY_STEP_STATE_CURRENT',
        'ORDER_HISTORY_STEP_STATE_FUTURE',
      ],
      default: 'ORDER_HISTORY_STEP_STATE_FUTURE',
      required: true
    }
  }]
})

有一次,我需要删除所有类型为“ORDER_HISTORY_LOCATION”的子文档,所以我正在运行:

let result = await Order.findOneAndUpdate(
  {orderId: req.params.orderId},
  {
    $pull: {
      history: {type: "ORDER_HISTORY_LOCATION"}
    }
  }, {new: true}
);

当我登录“result.history”时,我得到了这个:

CoreMongooseArray [
{ state: 'ORDER_HISTORY_STEP_STATE_CURRENT',
  _id: 5caf8a41641e6717d835483d,
  type: 'ORDER_HISTORY_DRIVER_DETAILS' },
{ state: 'ORDER_HISTORY_STEP_STATE_FUTURE',
  _id: 5caf8a41641e6717d835483c,
  type: 'ORDER_HISTORY_LOADING',
  date: 2019-05-08T09:00:00.000Z },
{ state: 'ORDER_HISTORY_STEP_STATE_FUTURE',
  _id: 5caf8a41641e6717d835483b,
  type: 'ORDER_HISTORY_LOADING',
  date: 2019-05-09T09:00:00.000Z },
{ state: 'ORDER_HISTORY_STEP_STATE_FUTURE',
  _id: 5caf8a41641e6717d8354837,
  type: 'ORDER_HISTORY_UNLOADING',
  date: 2019-05-13T09:00:00.000Z } ]

这是什么“CoreMongooseArray”?我不能用它做任何事情。我也找不到任何关于它的文档。

4

2 回答 2

13

CoreMongooseArray似乎继承了Array类型并且具有几乎相同的行为。

源代码(撰写本文时):https ://github.com/Automattic/mongoose/blob/3e523631daa48a910b5335c747b3e5d080966e6d/lib/types/core_array.js

如果您想将其转换为简单的数组,只需执行以下操作:

const history = Array.from(...result.history)

请注意,如果此数组包含对象,则每个对象都将具有不需要的附加 Mongoose 属性,因为它们是 Mongoose 模式文档。您需要将它们转换为纯 JavaScript 对象:

const history = Array.from(...result.history).map(v => v.toJSON())

希望能帮助到你。

于 2019-05-22T13:30:11.883 回答
2

这对我有用!

const history = Array.from([...result.history])
于 2021-02-02T18:57:28.203 回答