Node.js 如何在Mongoose查询对象中更新
我需要将特定评论的状态更改为Y,如果我在UI中单击“批准”按钮,我的文档结构如下所示Node.js 如何在Mongoose查询对象中更新,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我需要将特定评论的状态更改为Y,如果我在UI中单击“批准”按钮,我的文档结构如下所示 { "_id" : ObjectId("5a1fd0ffef39ff11ae353d10"), "file_name" : "Profile", "file_type" : "docx", "created_date" : ISODate("2017-11-28T10:29:10.373Z"), "updated_date" : ISODate("2017-11
{
"_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"
}
]
}
我尝试了一些已经在stackover flow中的查询,比如
mongo.filemanager.update(
{ "_id": req.body.id, "comments.comment_text": req.body.comments },
{ "$set": { "comments.$.status": 'Y' } }
)
但状态值并没有改变。我在这里用猫鼬
请在这个问题上帮助我。。提前谢谢
已更新
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")
}
);
我举了一个例子,看起来像你的案例,很有趣
您可以在中免费在线模拟mongodb终端以下是mongoose中更新的语法
Model.update(条件、更新、选项、回调)代码>
所以
$set
应该是第二个参数
试一试
您还可以使用findOneAndUpdate
mongo.filemanager.findOneAndUpdate(
{ "_id": req.body.id, "comments.comment_text": req.body.comments },
{
"$set": { "comments.status": 'Y' }
},
function(err,doc) {
}
);
谢谢你的回复。。。我试过了,但它不起作用。更新查询在猫鼬中会起作用吗?你怎么知道它不起作用?您正在查看更新结果吗?是的,我添加了$。。但是我的状态没有改变。顺便问一下,是否
req.body.comments
包含comments.comment\u text
?名称表明它包含注释数组或其他内容,而查询找不到要更新的文档。您的请求将更新注释
数组中的每个状态
。我仅将$set用作第二个参数。。。但我的评论状态不是getchanging@Vishnu,您还需要比较评论文本吗?非常感谢您……我已经尝试了您的第二个选择,$,这是格雷戈里·纽特(Grégory NEUT)提到的,它工作得很好……:)很高兴帮助您。:)谢谢你…我会再试一次非常感谢你它的工作。。。我使用了Sravan ans findOneAndUpdate和$…不太完美,非常感谢…:)
mongo.filemanager.findOneAndUpdate(
{ "_id": req.body.id, "comments.comment_text": req.body.comments },
{
"$set": { "comments.status": 'Y' }
},
function(err,doc) {
}
);