Search code examples
mongoose

deletMany and save behaving differently in Mongoose


I am using mongoose in express.js. My requirement is when a form is submitted using post, i need to delete the existing records and then save the new one.

When I use myModel.deleteMany({}), its not deleting. However it saves when I use myModel.save()

However if I use myModel.deleteMany({}).the(result=>{console.log(result)}), it deletes.

My doubt why I does deleteMany expect the promise to be consumed, for it to delete while save doesn't need such things

async function DoitFn(){
    Feedback.deleteMany({});
    console.log("Deleted");
}
app.post("/Process", function(req,res) {
    DoitFn();
    //Feedback.deleteMany({}).then((arg)=>{console.log(arg)});
    console.log("Post request");
    myFeedback = new Feedback ({
        Id: req.body.count,
        Rating:req.body.myRating,
        myView: req.body.myView
    })
    console.log(myFeedback.Rating);
    console.log(myFeedback.myView);
    myFeedback.save();
        result = Feedback.find().then(result=>{console.log(result);
        });
        return 1;
})

Solution

  • Mongoose queries are not promises, they have a then() function which will execute the query for you or you can use the async/await pattern. If you chain exec() when using async/await you will get better debugging capability because exec() will return a promise giving you a full stack trace in the event of an error.

    In your DoitFn() your Feedback.deleteMany({}); just prepares the query, nothing is executed.

    Whereas when you do Feedback.deleteMany({}).then((arg)...) the query is executed by the then() and the returned result is stored in the arg variable.

    I would recommend the following changes:

    async function DoitFn(){
       try{
          return await Feedback.deleteMany({}); //< use await keyword and return the result
       }catch(err){
          console.log('Error in DoitFn', err);
          throw err;
       }
    }
    
    
    app.post("/Process", async function(req, res) { //< mark callback as async
       console.log("Post request");
       try{
          const result = await DoitFn(); //< await the result
          console.log('Result of DoitFn = ', result);
          const myFeedback = new Feedback({
             Id: req.body.count,
             Rating: req.body.myRating,
             myView: req.body.myView
          });
          console.log(myFeedback.Rating);
          console.log(myFeedback.myView);
          await myFeedback.save(); //< need to use await here too
          const doc = await Feedback.find(); //< need to use await here too
          console.log('Found: ', doc);
          return res.status(200).json({
             message: 'Delete and create complete'
          })
       }catch(err){
          console.log('Error in app.post(/Process)', err);
          return res.status(500).json({
             message: 'Error on server'
          })
       }
    })