简体   繁体   中英

how to wait for model.save() in Mongoose

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?

Since you're passing a callback to save it will no longer return a promise so using await doesn't work.

If you want it to return a promise then don't pass a callback and you can use try-catch block for detecting errors:

const createNewUser = async (user) => {
  const newUser = new User();
  newUser.name = user.name;
  newUser.password = user.password;
  try {
    const result = await newUser.save();
    console.log(result);
  } catch (err) {
    console.log(err);
  }
};

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");
    }
}

You can use this shortcode too. If you need you can enclose that function in try-catch block.

async createNewUser (user) {
    const result = new User({
        name: user.name,
        password: user.password
    });
    console.log(await result.save())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM