Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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"}]}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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}
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!