如何将 findAndModify 与 Node.js MongoDB 驱动程序一起使用? [英] How to use findAndModify with a Node.js MongoDB driver?
问题描述
下面的代码有什么问题?
What is wrong with the code below?
db.get().collection('bars').findAndModify({
barID: req.body.button
},{
$push: {
usersfbID: req.body.profileUser[0].facebookID,
usersDocID: req.body.profileUser[0]._id
}
},{
new: true
}, function(err, doc){
if(err){
throw err;
}if(doc){
console.log('Existing document updated successfully');
console.log(doc);
}
});
我总是遇到同样的错误,
I always get the same error,
MongoError: 异常: nextSafe(): { $err: "无法规范化查询:BadValue 错误排序规范",代码:17287 }
MongoError: exception: nextSafe(): { $err: "Can't canonicalize query: BadValue bad sort specification", code: 17287 }
我做错了什么?我是否滥用了 $push 运算符?我是否需要在某些键值对周围提供引号?这个 findAndModify 方法让我发疯.我完全不知道我做错了什么.
What am I doing wrong? Am I misusing the $push operator? Do I need to provide quotes around some of the key value pairs? This findAndModify method is driving me crazy. I have absolutely no idea what I am doing wrong.
注意:我已经解决了关于 findAndModify 的其他问题,但这些解决方案都不适用于我.我确定这是一个关于函数语法的小错误.
Note: I have been through the other questions on SO regarding findAndModify, but none of those solutions is working for me. I'm sure its a small error regarding the syntax for the function.
推荐答案
findAndModify
方法具有以下签名
findAndModify(query, sort, doc, options, callback)
哪里
query
: 用于定位要修改的对象的查询对象.
sort
:如果多个文档匹配,则选择指定排序顺序中的第一个作为要操作的对象.doc
:要更新的字段/值.
options
optional:可选设置.
query
<object>
: The query object to locate the object to modify.sort
<array>
: If multiple docs match, choose the first one in the specified sort order as the object to manipulate.doc
<object>
: The fields/vals to be updated.options
<object>
optional: Optional settings.
您收到错误的原因是缺少 sort
规范,而是读取更新 doc
作为 sort
参数.
The reason why you are getting the error is because the sort
specification is missing and instead it's reading the update doc
as the sort
parameter.
您需要按如下方式指定排序参数:
You need to specify the sort parameter as follows:
db.get().collection('bars').findAndModify(
{ "barID": req.body.button }, // query
[ ["barID", 1] ], // sort
{
"$push": { // doc
"usersfbID": req.body.profileUser[0].facebookID,
"usersDocID": req.body.profileUser[0]._id
}
},
{ "new": true }, // options
function(err, doc){ // callback
if (err){
throw err;
} else if(doc){
console.log('Existing document updated successfully');
console.log(doc);
}
}
);
这篇关于如何将 findAndModify 与 Node.js MongoDB 驱动程序一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!