Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda