简体   繁体   中英

How can I delete an array entry in MongoDB with a delete API?

I am building an application that manages time sensitive tasks. I have APIs to create tasks and retrieve tasks, and I'm currently trying to get my delete API to work.

An employee has an array in MongoDB that contains todo tasks with text and I'm trying to delete the task by ID in SoapUI. With my current code, the delete request just sort of times out after a minute or so.

Here's my current delete API

router.delete("/:empId/tasks/:id", async (req, res) => {
  try {
    Employee.findByIdAndDelete(
      {
        empId: req.params.empId,
      },

      {
        $pull: {
          todo: {
            _id: req.params.id,
          },
        },
      }
    );
  } catch (e) {
    console.log(e);
    res.status(500).send({
      message: "Internal server error: " + e.message,
    });
  }
});

Current schema

let itemSchema = new Schema({
  text: { type: String },
  _id: { type: String },
});

task.service

  deleteTask(empId: number, task: string, _id: number): Observable<any> {
    return this.http.delete('/api/employees/' + empId + '/tasks/' + _id);
  }

and an example of an employee document in MongoDB

{"_id":{"$oid":"61797a51d15ad09b88d167af"},"empId":"1012", "firstName":"web","lastName":"developer","__v":1,"done":[],"todo":[{"_id":"1","text":"test"}]}

When you use findByIDAndDelete, it deletes that entire document. What you need is to update that particular document using update() / findOneAndUpdate() / findByIdAndUpdate() . Also you should either await/use a callback to return the value, like,

collection.findOneAndUpdate({_id:docId },{
        $pull: {"todo":{"_id":yourId} },
      },
      function(error, data){
           if(error){ return error}
           else {return data}
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM