[英]Mongoose how to do multiple updates
I'm having a tough time coming up with a solution to update multiple documents with different values. 我很难找到一个解决方案来更新具有不同值的多个文档。
I have an app that makes sales for every sold item I want to reduce the quantity in my database by one. 我有一个应用程序,可以让我想将数据库中的每个数量减少一个的每一项出售。
var soldItems =
[
{
"_id": "1"
"name": "Foo",
"price": 1.09
},
{
"_id": "2",
"name": "Bar",
"price": 2.00
}
]
var ids = [];
soldItems.forEach(function(item){
ids.push(item._id);
});
I'm collecting all the ids in my soldItems array of objects. 我正在收集我的soldItems对象数组中的所有ID。
Now I want to know how many items quantity I have in the database and then reduce the number quantity by one. 现在,我想知道数据库中有多少项目数量,然后将数量减少一。
ModelItem.find({_id: {$in: ids}}, function(err, docs){
if(err) throw err;
docs.forEach(function(doc){
soldItems.forEach(function(item){
if(doc._id === item._id){
doc.quantity += -1;
}
});
});
Item.update({_id: {$in: ids}}, {$set: docs }, function(err){
if(err) throw err;
});
});
Obviously this is wrong because $set is passing in array instead of an object. 显然这是错误的,因为$ set是在数组而不是对象中传递的。
I want to know how can I reduce the quantity by one for each item in my database, but I the same time I don't want to go below 0 items in the database. 我想知道如何减少数据库中每个项目的数量,但同时我不想降低数据库中的0个项目。
I'm sure im looking at this from the wrong angle. 我敢肯定,我是从错误的角度看的。
Thanks. 谢谢。
Use the $inc
operator instead, and the multi
options: 请改用$inc
运算符和multi
选项:
Item.update({_id: {$in: ids}, quantity: {$gt: 0}}, // selection
{$inc: {quantity: -1}}, // modifications
{multi: true}); //options
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.