Mongoose save() using native promise - how to catch errors
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.Promise
will 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
You are probably returning the promise created by method save to handle it somewhere else. If this is the case, you might want to throw the error to a parent promise where you can catch the error. You can achieve it with this:
function saveSchema(doc) { return doc.save().then(null, function (err) { throw new Error(err); //Here you are throwing the error to the parent promise });}function AParentPromise() { return new Promise(function (accept, reject) { var doc = new MongoSchema({name: 'Jhon'}); saveSchema(doc).then(function () { // this promise might throw if there is an error // by being here the doc is already saved }); }).catch(function(err) { console.log(err); // now you can catch an error from saveSchema method });}
I am not really sure if this might be an anti-pattern but this help you to handle your errors in one place.