I am able to run the following update command from command line:
db.Camera.update({_id:ObjectId("51059ca49c7b280809a2a81e")}, {$set: {"Selected":0}});
But the following code in NodeJS doesnt work. When I log item.Selected, I get a non-zero value.
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':idArray[i]}, function(err, item) {
item.Selected += 1;
console.log('Selected: ' + item.Selected);
collection.update({'_id':new BSON.ObjectID(ids[i])}, item,function(err, updated) {
if( err || !updated ) console.log("Not updated");
else console.log("Updated");
});
});
}
});
};
In the console, I always see “Not updated”.
Thanks for your help.
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 thefindOnereturns, the loop has already finished, meaning it’s really not what you expect asiwill be equal toids.length, for every “Camera.”You can just use the item’s
_idproperty 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
updatecall is what changed:Full code:
};