I am trying to catch errors thrown from Mongoose using Mongoose's native promises. But I don't know where to get the error object from Mongoose.
I would like the errors to be thrown in the .then()s and caught in .catch() if possible.
var contact = new aircraftContactModel(postVars.contact);
contact.save().then(function(){
    var aircraft = new aircraftModel(postVars.aircraft);
    return aircraft.save();
})
.then(function(){
    console.log('aircraft saved')
}).catch(function(){
    // want to handle errors here
});
Trying not to use another library, as .save() returns a promise natively.
While save() returns a promise, functions like Mongoose's find() return a Mongoose Query . Mongoose queries are thenables. In other words, queries have a then() function that behaves similarly to the Promise then() function. So you can use queries with promise chaining and async/await.
Built-in Promises This means that you can do things like MyModel. findOne({}). then() and await MyModel. findOne({}). exec() if you're using async/await.
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on.
MongooseJS uses the mpromise library which doesn't have a catch() method. To catch errors you can use the second parameter for then().
var contact = new aircraftContactModel(postVars.contact);
contact.save().then(function() {
    var aircraft = new aircraftModel(postVars.aircraft);
    return aircraft.save();
  })
  .then(function() {
    console.log('aircraft saved')
  }, function(err) {
    // want to handle errors here
  });
UPDATE 1: As of 4.1.0, MongooseJS now allows the specification of which promise implementation to use:
Yup
require('mongoose').Promise = global.Promisewill make mongoose use native promises. You should be able to use any ES6 promise constructor though, but right now we only test with native, bluebird, and Q
UPDATE 2: If you use mpromise in recent versions of 4.x you will get this deprication warning:
DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With