Reputation: 2913
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.
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.
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.
I'm sure im looking at this from the wrong angle.
Thanks.
Upvotes: 0
Views: 1024
Reputation: 5245
Use the $inc
operator instead, and the multi
options:
Item.update({_id: {$in: ids}, quantity: {$gt: 0}}, // selection
{$inc: {quantity: -1}}, // modifications
{multi: true}); //options
Upvotes: 2