删除特定集合数组的特定元素 - mongoDb

Deleting specific element of an array of a particular collection - mongoDb

我是 mongoDb 的新手。我创建了一个名为 task 的集合,该集合具有 comments 字段,该字段与其他字段一起是数组。 我需要删除任务的特定评论。每个评论中都有一个删除按钮。任务 ID 和评论 ID 都可用。 现在如何delete/edit任务的具体评论?

提前致谢

任务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,
});

任务路线

router.route('/').post((req, res) => {
  const { taskId } = req.body;
  Task.find(taskId)
    .then(task => {
      if (task) res.json({ status: true, task })
      else res.json({ status: false, msg: task not available.' })
    })
    .catch(err => res.status(400).json('Error: ' + err));
});

试试这个

Task.updateOne(
  { _id: taskId },
  {
    $pull: { comments: { 'comment_id': commentId } }
  }
);

MongoDB 也采用驼峰式命名,因此将 comment_id 字段重命名为驼峰式命名(或什至简单地 id)可能会提高可读性。