Following.follow = function(id1,id2,cb) { console.log(id1) //返回Matt console.log(id2) //返回Simone
Following.collection.findAndModify({
query: {
ownerId: id1
},
update: {
$addToSet: {
followedBy: id2
}
},
upsert: true,
new: true
}, function(err, result, lastErrorObject) {
cb(err, result)
console.log(result) // returns null
})
}我正在使用Mocha运行测试,而我的findAndModify函数将只返回null。我阅读了文档,但似乎找不到我做错了什么。如果没有找到,Upsert和true组合起来应该会生成文档,而new应该返回修改后的对象。
发布于 2015-08-25 18:20:34
看起来这在很多方面都是错误的:
首先,这里的.findAndModify()语法对于任何node.js驱动程序都是无效的,您可能指的是.findOneAndUpdate():
Following.collection.findOneAndUpdate({
{ "ownerId": id1 },
{ "$addToSet": { "followedBy": id2 } },
{
"upsert": true,
"returnOriginal": false
},
function(err, result) {
console.log(result); // if you don't call before the callback it never gets called.
cb(err, result);
}
);第二种情况是,这里的.collection暗示这是来自" mongoose ",所以使用mongoose为.findOneAndUpdate()提供的本机方法
Following.findOneAndUpdate({
{ "ownerId": id1 },
{ "$addToSet": { "followedBy": id2 } },
{
"upsert": true,
"new": true
},
function(err, result) {
console.log(result); // if you don't call before the callback it never gets called.
cb(err, result);
}
);如果你传递的字符串需要像ObjectId这样的大小写,而不是手动处理,那么最后可能就是你想要的。Mongoose会处理这个问题。本机驱动程序不会为您做这件事,因为它没有可引用的“模式”来实现“类型转换”。
因此,请使用应该支持的方法。
https://stackoverflow.com/questions/32201197
复制相似问题