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

2K
Visualizações
Remove referenced documents with mongoose/MongoDB middleware (in 2021 )

I tried all the solutions over stack overflow which relate to deleting referenced documents in MongoDB using node.js. But most of them either have solutions with deprecated methods and some of them do not work at all.

I have two models, Parent and Child with one-to-many relationship. The parent document includes array of referenced children documents id's as shown in the following schema.

//file => parent.js 

const parentSchema = new mongoose.Schema({
  parentName: {
    type: String,
  },
  childrens : [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Children'
    }
  ]
});

const Parent = mongoose.model("Parent", parentSchema);
module.exports = Parent ; 

Next file has children model with childrenSchema.pre() middleware or hook which is triggered successfully -

//file => children.js 

const mongoose = require("mongoose");
const Parent  = require("./parent"); 


const childrenSchema = new mongoose.Schema({
  childrenId: Number,
  info: String,
  type: String, 
});


childrenSchema.pre('findOneAndDelete', async function(next) {
  console.log('trigger when middleware runs' , this.getQuery()["_id"]) ; 

  const childrenId = new mongoose.Types.ObjectId(this.getQuery()["_id"])
  await Parent.updateOne({} , { $pull: { childrens: { _id: childrenId }}});
  next()
}) 


const Children = mongoose.model("Children", childrenSchema);
module.exports = Children ; 

Now, finally this is the route that I am calling to delete the instance of childrenId. I have got quite a few errors but mainly it says that Parent.updateOne()is not a function in the above file. But middleware is triggered successfully when the below route is executed.

// route which performs delete action and triggers mongoose middleware

router.delete('/delete/instance' , async(req,res) => {
  const childrenId = new mongoose.Types.ObjectId('612cd0d8f9553c9f243db691')
  
  const deletedInstance = await Children.findOneAndDelete(
      { _id: childrenId}
  )
  res.json(deletedInstance)

})
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Note that you are trying to perform updateOne() with no filter option. For the logic itself, why don't you put it inside the router:

const Parent  = require("./parent"); 

router.delete('/delete/instance' , async (req,res) => {
  await Parent.updateOne({ childrens: '612cd0d8f9553c9f243db691' }, { $pull: { childrens: '612cd0d8f9553c9f243db691' }})
  const deletedInstance = await Children.findOneAndDelete({ _id: '612cd0d8f9553c9f243db691'})
  res.json(deletedInstance)
})
over 4 years ago · Santiago Trujillo 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