我有这个模式:
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”?我对此无能为力。我也找不到任何文档。
答案 0 :(得分:2)
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())
希望有帮助。
答案 1 :(得分:2)
这对我有用!
const history = Array.from([...result.history])