【发布时间】:2015-07-10 02:44:31
【问题描述】:
我正在尝试使用 findByIdAndUpdate 更新 Mongoose 模型
为了这个问题,模型被称为ItemVariant,它继承自Item。
有效载荷数据的一个例子是:
var data = {
arrayField: [ 1, 3 ],
description: 'This is a description' }
}
如果我打电话
ItemVariant.findByIdAndUpdate(objectId, data);
我可以看到描述得到了更新,但是 arrayField 根本没有传递给 mongo - 实际上所有数组都被删除了数据对象。
我一直试图弄清楚如何做到这一点,查看了为数组设置$pushAll,但似乎没有任何效果。
这里有什么我遗漏的吗?
模型架构是继承的。 Mongoose 模型如下所示:
function ItemVariantSchema() {
var self = this;
Schema.apply(this, arguments);
self.add({
description: [String],
arrayField: [Number]
});
}
util.inherits(ItemVariantSchema, ItemSchema);
// the field that represents the sub-class discriminator
var schemaOptions = {
discriminatorKey: 'type'
};
// create ItemVariant schema
var itemVariantSchema = new ItemVariantSchema({}, schemaOptions);
// create ItemVariant model
Item.discriminator('Variant', itemVariantSchema);
// Export the ItemVariant schema
module.exports = ItemVariantSchema;
mongod --verbose 输出示例:
command: findAndModify { findandmodify: "itemvariants", query: { _id: ObjectId('5541fb680dc0e9223bea1ddb') }, new: 1, remove: 0, upsert: 0, update: { $set: { description: "EDIT: some description" } } } update: { $set: { description: "EDIT: some description" } } nscanned:1 nscannedObjects:1 nMatched:1 nModified:0 keyUpdates:0 numYields:0 locks(micros) w:104 reslen:358 0ms
如您所见,arrayField 已被删除
我也尝试过类似的方法:
var data = {
$set: { description: 'This is a description' },
$push: { arrayField: [ 1, 3 ] }
}
但是 $push 数组在到达 mongo 时似乎是空的。
正如@chridam 所建议的,我也尝试过类似的方法:
var data = {
$set: {
description: 'some description'
},
$addToSet: {
arrayField: {
$each: [2, 3]
}
}
}
现在的输出如下所示:
command: findAndModify { findandmodify: "itemvariants", query: { _id: ObjectId('5541fb680dc0e9223bea1ddb') }, new: 1, remove: 0, upsert: 0, update: { $set: { description: "EDIT: another description" }, $addToSet: { arrayField: {} } } } update: { $set: { description: "EDIT: another description" }, $addToSet: { arrayField: {} } } nscanned:1 nscannedObjects:1 nMatched:1 nModified:1 keyUpdates:0 numYields:0 locks(micros) w:118 reslen:366 0ms
【问题讨论】:
标签: arrays node.js mongodb mongoose