Id like to update an array and return the doc. Is my findAndModify syntax correct?
this.becomeFollower = function(title, username, callback){
"use strict"
posts.findAndModify({
query: {"title":title, "roster":"yes"},
update: { "$addToSet": { "followers":username } },
new: true,
upsert: true
},
function(err, doc){
console.log('find and modified ' +doc);
});
}
I had no problem using this:
posts.update({"title":title, "roster":"yes"}, { "$addToSet": { "followers":username } }, function(err, roster){
"use strict"
if(err) return callback(err, null);
callback(err, roster);
});
Check out the docs for node-mongodb findAndModify; the signature looks like:
collection.findAndModify(query, sort, update, options, callback)
So you should do:
posts.findAndModify(
{"title":title, "roster":"yes"},
[['_id','asc']],
{ "$addToSet": { "followers":username } },
{new: true, upsert: true},
function(err, doc){
console.log('find and modified ' +doc);
}
);
The sort
argument is probably optional, but it's unclear so I included it in the example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With