我正在尝试修改另一个人编写的一段代码。
我需要更新mongodb文档而不是删除它。
这是代码:
const docs = await docsModel.find({});
for (const doc of docs) {
doc.remove();
}
我需要更新而不是删除。我已经尝试过了:
const docs = await docsModel.find({});
for (const doc of docs) {
doc.updateOne({field_I_want_to_update : "new_value"});
}
但这不起作用。
有什么建议吗?
答案 0 :(得分:1)
视情况而定。
如果您要使用相同值更新多个文档,那么最好是:
doc.updateMany(<filter>, { $set: { field_I_want_to_update : "new_value" } });
其中:<filter>
类似于:{ _id: <validId> }
或{ _id: { $in: [<array_of_ids>] } }
如果您要使用 dynamic 值更新多个文档,则可以这样做:
const docs = await docsModel.find({});
docs.forEach(function(doc) {
await docsModel.updateOne({ _id: doc._id }, { $set: { field_I_want_to_update: "new_dynamic_value" } });
});
与您的情况相比,您缺少第一个参数<filter>
,第二个您需要以$set: { <field>: <value> }
开头,而不是以{ <field>: <value> }
答案 1 :(得分:1)
您可以使用猫鼬updateMany
函数,该函数接受过滤器以及键和值的对象进行更新。将对象包装在$set
属性中。从理论上讲,您可以循环使用findByIdAndUpdate
,但这是资源浪费。
所以像
await docsModel.updateMany({}, {$set: { /*insert field name*/: /*insert field value*/ } });