我有一个集合,并希望更新或创建新的文档和$inc计数器。
我尝试过移动update / upsert对象,但没有效果。
蒙古版本为3.0.11。
update = {
query: {
_id: "ABCDEFG1234"
},
update: {
$setOnInsert: {
$inc: {
counter: 1
}
}
},
new: true,
upsert: true
}
DB.collection('stats').findAndModify(update,function(e,d) { if (e) { console.log(e);} })
/*
{ MongoError: need remove or update
at Function.MongoError.create (~/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
at commandCallback (~/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1154:66)
at Callbacks.emit (~/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
at .messageHandler (~/mongodb/node_modules/mongodb-core/lib/topologies/server.js:295:23)
at Socket.<anonymous> (~/mongodb/node_modules/mongodb-core/lib/connection/connection.js:285:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:172:18)
at Socket.Readable.push (_stream_readable.js:130:10)
at TCP.onread (net.js:542:20)
name: 'MongoError',
message: 'need remove or update',
ok: 0,
errmsg: 'need remove or update' }
*/更新
我试过了
var find = { member_id: "ABCDEFG1234" };
var update = { $set: { update: Date.now() }, $inc: { web_visit: 1 } };
var options = { new: true, upsert: true, };
DB.collection('stats').findAndModify(find,update,options,function(e,d) {
if (e) { console.log(e);}
});但现在,它默默地失败了,在'stats‘集合中什么也没有。
发布于 2016-10-28 10:02:08
您的更新查询组合错误;您是嵌套操作符,这只会抛出一个错误。因为您想要的操作是设置一个计数器字段并在更新中增加它,所以一个$inc运算符就足够了,因为如果计数器字段不存在,$inc将创建该字段并将该字段设置为指定的值。
因此,使用Node.js驱动程序的findAndModify()方法签名进行正确的更新操作如下:
DB.collection("stats").findAndModify(
{ "_id": "ABCDEFG1234" }, // query object to locate the object to modify
[["_id", "asc"]], // sort array
{ "$inc": { "counter": 1 } }, //document (object) with the fields/vals to be updated
{ "new": true, "upsert": true }, // options to perform an upsert operation.
function(error, doc) { if (doc) { console.log(doc); } }
);https://stackoverflow.com/questions/40302084
复制相似问题