findOneAndUpdate与returnNewDocument一起使用:true返回原始文档MongoDB
您好我使用MongoBD与节点js,我用npm install mongodb
我想要更新现有的文档并返回更新的文档,文档已正确更新。 但是它返回的旧文件是指更新前的原始文件。 我已经使用了returnNewDocument:true
参数,但没有用。
var filter = { '_id': object_id }, update = { $set: { "status" : data["status"] }, $push: { "statusHistory": { $each: [{ status:data["status"],statusChangedTime:data["statusChangedTime"],comment:data["comment"]}], $position:0, } }, } ,options = { //upsert: false, //multi: false, returnNewDocument: true }; col.findOneAndUpdate(filter, update, options,function(err, res) { if (err) { console.log(err); }else { console.log(res); } });
答复是
{ lastErrorObject: { updatedExisting: true, n: 1 }, value: { //original document }, ok: 1 }
当我通过terminal直接去mongoDB并尝试
db.MyCollection.find().pretty();
该文件正确更新,它只是返回原来的而不是更新的。
在这里停留2小时,任何帮助表示赞赏
在package.json中
"mongodb": "^2.1.4",
Node.js 驱动程序文档没有提到findOneAndUpdate()
(这是具有相同名称的MongoDB shell命令的选项findOneAndUpdate()
的returnNewDocument
选项。
相反,它提到了一个名为returnOriginal
的选项,默认为true
。 尝试使用该选项,将其设置为false
以返回更新的文档而不是原始文档。
节点js mongoDb驱动程序已经从mongo shell命令中分化出来了。 如果你正在使用“mongodb”:“^ 2.1.4”,那么使用
returnOriginal:false
代替
returnNewDocument:true
。
让我们看看下面的代码:
db.collection('user_setting').findOneAndUpdate({user_id: data.user_id}, {$set: data}, {projection: dbConfig.userSetting, returnOriginal: false}, function (err, res) { if (err) { callback({'error': 1, 'message': 'Internal server error! ' + err, 'data': null, 'status': 500}); } else { console.log(res); /* { lastErrorObject: { updatedExisting: true, n: 1 }, value: { user_id: 1, notification_alert: 1, notification_sound: 1, user_setting_id: 2 }, ok: 1 } */ } });