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

2K
Views
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 answers
Answer question

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 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!