【问题标题】:Getting CoreMongooseArray instead of normal array获取 CoreMongooseArray 而不是普通数组
【发布时间】:2019-09-02 12:15:51
【问题描述】:

我有这个架构:

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”?我不能用它做任何事情。我也找不到任何文档。

【问题讨论】:

  • 这也让我发疯了,我正在尝试升级到 Mongoose 5,但我们的许多测试都失败了,因为它们正在使用普通数组进行相等性检查

标签: node.js database mongodb mongoose nosql


【解决方案1】:

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())

希望对你有帮助。

【讨论】:

  • 谢谢,我将此标记为答案,因为它给出了很好的解释。事实证明我有一个错字,我的代码在我更正后继续工作。这很尴尬,因为我得到的错误似乎与错字无关,这就是为什么很难找到错误的原因。谢谢。
【解决方案2】:

这对我有用!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 2017-08-27
    • 1970-01-01
    相关资源
    最近更新 更多