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

167
Views
How can I use mongoose to delete something in an array using an API?

I'm building a todo app and in the database have an employee document containing 2 arrays (todo & done). The tasks are stored here, and I currently can add tasks to the arrays, but I'm having trouble figuring out how to get my API work to delete them.

Here's what my employee doc looks like

    {"_id":{"$oid":"61797a3ed15ad09b88d167ab"},"empId":"1008","password":"password2","firstName":"test","lastName":"user","__v":5,"done":[],"todo":[{"_id":{"$oid":"61870bfe6ac33427b8406f7d"},"text":"testtask","id":"1"}]}

Currently I receive errors when trying to test using SoapUI, many similar to this "TypeError: Cannot read property 'findByIdAndDelete' of undefined" or Cannot DELETE /api/employees/1007/6184645df6bbd93340c0e390

Here's my delete API

*
 * Delete task
 */
router.delete("/:empId/tasks/:id", async (req, res) => {
  try {
    Employee.findByIdAndDelete(
      { _id: req.params.id },
      function (err, employee) {
        if (err) {
          console.log(err);
          res.status(500).send({
            message: "Internal server error: " + err.message,
          });
        } else {
          console.log(employee);

          console.log(
            "Task with the id of" +
              req.params.id +
              " has been deleted successfully"
          );
          res.json(employee);
        }
      }
    );
  } catch (e) {
    console.log(e);
    res.status(500).send({
      message: "Internal server error: " + e.message,
    });
  }
});

Currently, I can get messages to the console saying it's been deleted but it hasn't actually deleted in the database

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Welcome to stackoverflow! You should use updateOne with $pull. Try:

Employee.updateOne({
  empId: req.params.empId
}, {
  $pull: {
    todo: {
      _id: req.params.id
    }
  }
})

Reference: https://stackoverflow.com/a/27917378/9459826

MongoDB docs: https://docs.mongodb.com/manual/reference/operator/update/pull/

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!