Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose save() using native promise - how to catch errors

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.

like image 798
steampowered Avatar asked Jul 14 '15 01:07

steampowered


People also ask

Does Mongoose save return a promise?

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.

What is promise in Mongoose?

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.

Is Mongoose save async?

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on.


1 Answers

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
like image 76
Jason Cust Avatar answered Sep 27 '22 17:09

Jason Cust