我是mongoDb的新手。我创建了一个名为task的集合,该集合具有注释字段,该字段与其他字段一起为数组。我需要编辑任务的具体评论。每个评论中都有一个编辑按钮。任务id和注释id都可用。现在如何编辑任务的具体注释?
提前感谢
任务api
{
"status":true,
"task":[
{
"_id":"61dfef323a6ee474c4eba926",
"description":"hello there",
"title":"hello",
"comments":[
{
"comment_id":1,
"username":"test",
"comment":"abcd",
"status":true,
},
{
"comment_id":2,
"username":"test",
"comment":"abcdsdfsdf",
"status":true,
}
],
"createdAt":"2022-01-13T09:21:54.795Z",
"updatedAt":"2022-01-13T09:21:54.795Z",
"__v":0
}
]
}
任务模型模式
const taskSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
comments: [Object],
}, {
timestamps: true,
});
我尝试过使用$set,但我不知道如何在内部数组中使用它。
router.route('./comments/edit').post((req, res) => {
const commentId = req.body.commentId;
const taskId = req.body.postId;
const comment = req.body.editedComment;
const updatedAt = new Date();
Task.updateOne(
{ _id: taskId},
{
//what to do here?
// $set: { comments: [ {'comment_id': commentId} ]},
}
)
.then((response) => res.json({ status: true, msg: 'Comment Edited!' }))
.catch(err => res.json({ status: false, msg: err }));
});
提前谢谢。
这就是如何做到最好:
db.collection.update({
status: true
},
{
$set: {
"task.$[x].comments.$[y].username": "New Name"
}
},
{
arrayFilters: [
{
"x._id": "61dfef323a6ee474c4eba926"
},
{
"y.comment_id": 2
}
]
})
解释:
- 在update语句中将x和y定义为arrayFIlters
- 在$set语句中,提供x&y过滤器以识别要更新的特定注释
在示例中,我更新了用户名,但您可以更新由x&y.
操场
以下是如何在同一嵌套数组元素中同时更新两个值。