如果我单击 UI 中的批准按钮,我需要将特定评论的状态更改为 Y,我的文档结构如下。
{
"_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"
}
]
}
我尝试了一些已经在堆栈流中的查询,例如
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 中 update 的语法。
Model.update(条件、更新、选项、回调);
所以,
$set
应该是第二个参数,
尝试
mongo.filemanager.update({ "_id": req.body.id, "comments.comment_text": req.body.comments },{ "$set": { "comments.status": 'Y' } })
Mongoose official Documentation
您还可以使用findOneAndUpdate
,
mongo.filemanager.findOneAndUpdate(
{ "_id": req.body.id, "comments.comment_text": req.body.comments },
{
"$set": { "comments.status": 'Y' }
},
function(err,doc) {
}
);
关于node.js - 如何在 Mongoose 查询对象中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47571226/