Search code examples
mongodbmern

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


I am new to mongoDb. I have created a collection named task that has comments field which is array along with other fields. I need to delete specific comment of the task. There is a delete button in each comment. Both task id and comment id are available. Now how to delete/edit specific comment of the task?

Thanks in advance

task 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
      }
   ]
}

Task model schema

const taskSchema = new Schema({
  title: { type: String, required: true },
  description: { type: String, required: true },
  comments: [Object],
}, {
  timestamps: true,
});

task route

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));
});

Solution

  • Try this

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

    Also MongoDB embraces camelCase, so renaming comment_id field to camelCase (or even simply id) might improve readability.