我正在使用带有节点js的MongoDB 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);
}
});
Run Code Online (Sandbox Code Playgroud)
反应是
{ lastErrorObject: { updatedExisting: true, n: 1 },
value:
{
//original document
},
ok: 1 }
Run Code Online (Sandbox Code Playgroud)
当我直接通过终端去mongoDB并尝试
db.MyCollection.find().pretty();
Run Code Online (Sandbox Code Playgroud)
文档正确更新,它只返回原始文件而不是更新的文件.
被困在这里2个小时,任何帮助表示赞赏
在package.json中 …
我的应用程序使用Mongoose并具有使用timestamps选项的模式:
var fooSchema = new Schema({
name: String,
}, {
timestamps: true,
});
mongoose.model('Foo', fooSchema);
Run Code Online (Sandbox Code Playgroud)
因此,只要将更新写入集合,该updatedAt属性就会更改为当前日期.但是现在我想添加一些不应该更新updatedAt属性的更改.Stackoverflow(示例)上的一些答案建议使用Foo.collection,因为据称访问本机MongoDB驱动程序.所以我尝试了这个:
Foo.collection.update({ _id: someFooId }, { $set: { name: 'New Name' } });
Run Code Online (Sandbox Code Playgroud)
然而,这也改变了updatedAt财产.
那么如何在不更改的情况下更新文档updatedAt?
我有:
Emotion.find (query, "-_id", opts, function (error, e){
if (error) return cb (error, 500);
for (var i=0, len=e.length; i<len; i++){
e[i] = convert (e[i]);
}
cb (null, e);
});
Run Code Online (Sandbox Code Playgroud)
如果函数返回 1k 个文档,我必须迭代 1k 次。
如何添加为每个文档执行的回调?就像是:
var each = function (e){
return convert (e);
};
Emotion.find (query, "-_id", opts, each, function (error, e){
if (error) return cb (error, 500);
cb (null, e);
});
Run Code Online (Sandbox Code Playgroud)
我基本上需要使用来自 mongodb 的 each():http : //mongodb.github.com/node-mongodb-native/api-generated/cursor.html#each
编辑:也许这可以通过从流中侦听数据事件并将文档推送到数组来完成: