gpt4 book ai didi

arrays - Mongoose 从 findByIdAndUpdate 中移除数组(继承模式)

转载 作者:可可西里 更新时间:2023-11-01 10:03:46 30 4
gpt4 key购买 nike

我正在尝试使用 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

最佳答案

您需要使用 $set运算符(operator):

var data = {
"arrayField": [ 1, 3 ],
"description": "This is a description"
};

ItemVariant.findByIdAndUpdate(objectId, { "$set": data });

-- 更新 --

尝试使用 $set 的组合description 字段和 $addToSet 的更新运算符运算符 $each arrayField 数组字段上的修饰符。 $each修饰符允许 $addToSet将多个值添加到数组字段的运算符:

var data = {
"arrayField": [ 1, 3 ],
"description": "This is a description"
};

var update = {
"$set": {
"description": data.description
},
"$addToSet": {
"arrayField": {
"$each": data.arrayField
}
}
};

ItemVariant.findByIdAndUpdate(objectId, update, options, callback);

关于arrays - Mongoose 从 findByIdAndUpdate 中移除数组(继承模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29967032/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com