我想更新数组并返回文档。我的findAndModify语法是否正确?
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);
});
}
使用它我没有问题:
posts.update({"title":title, "roster":"yes"}, { "$addToSet": { "followers":username } }, function(err, roster){
"use strict"
if(err) return callback(err, null);
callback(err, roster);
});
答案 0 :(得分:15)
查看docs for node-mongodb findAndModify;签名如下:
collection.findAndModify(query, sort, update, options, callback)
所以你应该这样做:
posts.findAndModify(
{"title":title, "roster":"yes"},
[['_id','asc']],
{ "$addToSet": { "followers":username } },
{new: true, upsert: true},
function(err, doc){
console.log('find and modified ' +doc);
}
);
sort
参数可能是可选的,但它不清楚所以我将它包含在示例中。