如何在Mongoose查询对象中更新

我需要改变状态为Y特殊评论,如果我点击批准的button在UI中,我的文档结构如下。

{ "_id" : ObjectId("5a1fd0ffef39ff11ae353d10"), "file_name" : "Profile", "file_type" : "docx", "created_date" : ISODate("2017-11-28T10:29:10.373Z"), "updated_date" : ISODate("2017-11-28T12:39:32.148Z"), "comments" : [ { "created_date" : ISODate("2017-11-28T13:23:51.472Z"), "status" : "N", "comment_text" : "Yes...", "username" : "Vishnu" }, { "created_date" : ISODate("2017-11-28T13:24:15.938Z"), "status" : "N", "comment_text" : "Yes...", "username" : "Vishnu" }, { "created_date" : ISODate("2017-11-28T13:28:44.455Z"), "status" : "N", "comment_text" : "fsdfdsf", "username" : "T" }, { "created_date" : ISODate("2017-11-28T13:29:22.132Z"), "status" : "N", "comment_text" : "fdsfsdf", "username" : "dasdas" }, { "created_date" : ISODate("2017-11-28T13:29:46.247Z"), "status" : "N", "comment_text" : "fdgdfgfd", "username" : "Vishnu T" } ] } 

我已经尝试了一些已经在stackoverstream中的查询

  mongo.filemanager.update( { "_id": req.body.id, "comments.comment_text": req.body.comments }, { "$set": { "comments.$.status": 'Y' } } ) 

但是地位价值并没有变化。 我在这里使用mongoose。

请帮助我在这个问题上..在此先感谢

更新

 mongo.filemanager.findOneAndUpdate( { "_id": req.body.id, "comments.comment_text": req.body.comments }, { "$set": { "comments.$.status": 'Y' } }, function(err,doc) { if (err) throw err console.log("Updated Commentstatus") } ); 

这里是mongoose更新的语法。

Model.update(conditions, update, options, callback);

所以,

$set应该是第二个参数,

尝试

 mongo.filemanager.update({ "_id": req.body.id, "comments.comment_text": req.body.comments },{ "$set": { "comments.status": 'Y' } }) 

mongoose官方文档

你也可以使用findOneAndUpdate

 mongo.filemanager.findOneAndUpdate( { "_id": req.body.id, "comments.comment_text": req.body.comments }, { "$set": { "comments.status": 'Y' } }, function(err,doc) { } ); 

我做了一个例子,看起来像你的情况,有趣的。

在这里输入图像说明


您可以在这里免费模拟在线mongodbterminal