Difference on Mongoose using Promise or Async/Await?

Viewed 2373

Using ExpressJs (as Web framework for Node.js) and Mongoose (for modeling MongoDB) to create a web service. I had a question about the best approach to handle the return object from some mongoose methods as (save, find, findByIdAndDelete, etc).

As the mongoose documentation says, the Model.prototype.save() will returns «Promise,undefined» Returns undefined if used with callback or a Promise otherwise. For more: https://mongoosejs.com/docs/api.html#model_Model-save

So i want to know which one should we use or on which case one is better that the other?

As example using ES7 Async/Await:

const mongoose = require('mongoose');
const Person = mongoose.model('person');

module.exports.savePerson = async (req,res) => {
  await new Person( {...req.body} )
    .save( (err, doc)=> {
      err ? res.status(400).json(err) : res.send(doc);
    });
}

As example using ES6 Promise:

const mongoose = require('mongoose');
const Person = mongoose.model('person');

module.exports.savePerson = (req,res) => {
  const person = new Person( {...req.body} )

  person.save()
    .then(person => {
      res.send(person);
    })
    .catch(err => {
      res.status(400).json(err)
    });
}
1 Answers

Don't use a callback if you want to await it:

 module.exports.savePerson = async (req,res) => {
   try {
     const doc = await new Person( {...req.body} ).save();
     res.send(doc);
   } catch(error) {
     res.status(400).json(err);
   }
};

So i want to know should we use [.thens] or [awaits] ?

Thats opinion based, but in my eyes await is way more readable, especially when you have to wait for multiple things.


Security advise: Directly passing the clients data to the database without validation is a bit dangerous.

Related