[英]update many nested objects in mongoose
is there a way to update many nested objects in mongoose all at once ? 有没有办法一次更新猫鼬中的许多嵌套对象? i can update one nested object like this :
我可以像这样更新一个嵌套对象:
Model.findOneAndUpdate(
{name : watchlistName , "mentions.id" : 123},
{
$set : {
"mentions.$.tone" : positive,
"mentions.$.verified" : true
}
}, function (err) {
if(err) {
console.log(err);
}
}
);
but if i have let's say 200 id to update, how should i proceed ? 但是如果我说要更新200个id,我应该如何进行?
You can use Model's update method for this. 您可以为此使用模型的更新方法。
Model.update(
{name : watchlistName , "mentions.id": { $in: [1, 2, 3, 4, 5] }},
{
$set : {
"mentions.$.tone" : positive,
"mentions.$.verified" : true
}
}, function (err) {
if(err) {
console.log(err);
}
}
);
If you need to update them with different values I'd suggest to do it this way: 如果您需要使用不同的值来更新它们,建议您这样做:
const docs = await Model.find({name : watchlistName , "mentions.id": { $in: [1, 2, 3, 4, 5] }}).exec();
docs.forEach((doc) => {
doc.mentions.$.tone = '[docValue]';
});
await Promise.all(docs.map(async doc => await doc.save()));
// All docs are updated now
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.