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