Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda