我想更新一个数组并返回文档。我的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);
});
最佳答案
查看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
参数可能是可选的,但尚不清楚,因此我将其包含在示例中。关于javascript - findAndModify-MongoError : exception: must specify remove or update,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22671946/