The id inside the loop isn't what you expect because of your use of the variable i
. These are callbacks, inside a closure. So, when the findOne
returns, the loop has already finished, meaning it's really not what you expect as i
will be equal to ids.length
, for every "Camera."
You can just use the item's _id
property directly when your code calls update (or anything else you'd like, just don't rely on the loop index, unless you wrap the code within the loop all with a closure which likely isn't necessary).
Something like this ... the query parameter to update
call is what changed:
{'_id':item._id)}
Full code:
exports.findById = function(req, res) { var ids = req.params.id.split(","); db.collection('Camera', function(err, collection) { for(var i = 0; i < ids.length; i++){ collection.findOne({'_id':ids[i]}, function(err, item) { item.Selected += 1; console.log('Selected: '+ item.Selected); collection.update({'_id':item._id)}, item,function(err, updated) { if( err || !updated ) console.log("Not updated"); else console.log("Updated"); }); }); } });
};