Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose await save

In my Nodejs project I would just like to await a mongoose.save function before continuing with my code. The below example does not work, but can anyone help me with something that will work please.

app.post('/api/CreateUser', async (req, res) => {
    const newUser = new User({
        'email': req.body.email,
        'name': req.body.name
    });
    console.log('before save');
    await newUser.save((err, userDoc) => {
        if (err) return res.status(400).send(err);
        console.log('saved item');
    });
    console.log('after save');
});

The current console.log order is:

  1. before save
  2. after save
  3. saved item

But I would like it to be:

  1. before save
  2. saved item
  3. after save
like image 750
Freddy Bonda Avatar asked Oct 16 '18 09:10

Freddy Bonda


1 Answers

Please change code with try and catch.

Also, check how to use await.

try {
  const newUser = new User({
    'email': req.body.email,
    'name': req.body.name
  });
  console.log('before save');
  let saveUser = await newUser.save(); //when fail its goes to catch
  console.log(saveUser); //when success it print.
  console.log('after save');
} catch (err) {
  console.log('err' + err);
  res.status(500).send(err);
}
like image 87
IftekharDani Avatar answered Sep 19 '22 11:09

IftekharDani