Home > Net >  Mongodb delete where parent does not exist
Mongodb delete where parent does not exist

Time:11-16

I have a collection called faculty and another collection called program, if I want to delete faculty I need to check if faculty is not exist in any program, I mean faculty id is not associated with any program

Why this code is not working!!!

 //Delete faculty
 router.delete('/:id',(req,res)=>{
    let programCount = Program.find({faculty:req.params.id}).count();
    if(programCount > 0)
    {
        console.log('don\'t delete this')
    }

CodePudding user response:

you are using synchronous function in your router

thus,

you conditional statement if(programCount > 0) is already executed while the Program.find isn't finish yet. Use async/await

//Delete faculty
router.delete("/:id", async (req, res) => {
  let programCount = await Program.find({ faculty: req.params.id }).count();
  if (programCount > 0) {
    console.log("don't delete this");
  }
});
  • Related