how to wait for model.save() in Mongoose Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of how to wait for model.save() in Mongoose without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a function like so:

createNewUser async (user) {
    const newUser = new User();
     newUser.name = user.name;
     newUser.password = user.password;
     let result = await newUser.save((err, data) => {
         if (err) return err;
         console.log(data);
         return data;
     })
     console.log(result) // Undefined
}

The result return undefined and it run BEFORE the console.log(data) which very weird. Is there any way to get the result of newUser.save() either it be error or the data that successfully saved?

Answer

You don’t have to use callback if you want to use async/await or promises. This moment is clearified in documentation.

So, correct code:

async createNewUser (user) {
    const newUser = new User();
    newUser.name = user.name;
    newUser.password = user.password;

    const result = await newUser.save();
    console.log(result); // result
}

And if you need to proccess errors (what is strongly recommended, but in your code error handler doesn’t do anything), you can just wrap it into try/catch:

async createNewUser (user) {
    const newUser = new User();
    newUser.name = user.name;
    newUser.password = user.password;

    try {
      const result = await newUser.save();
      console.log(result); // result
    } catch (err) {
      console.error("something goes wrong");
    }
}
We are here to answer your question about how to wait for model.save() in Mongoose - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji