Jacky Chiu Jacky Chiu - 3 months ago 36
Node.js Question

Mongoose error handling with Promises

I'm using mongoose with native ES6 promises for database management in my Nodejs, REST API.

I'm having trouble finding best practices with error handling. I have a section of code that looks like this:

Cities.findOne({'id': someid}).then((city) => {
if (!city) throw 'No city found';
//modify city.embedded.dynamic.field
return city.save();
}).then((city) => {
if (!city) throw 'City not saved';
res.send(city);
}).catch((err) => {
console.log(err);
});


Is it necessary for me to check if the return of the
city.save()
is undefined? Or will an error in the save be caught in the catch?

It's unclear in the docs whether or not
save()
could return
undefined
like how mongoose queries sometimes do.

Any help would be appreciated.

Edit: I'm using
findOne
and manually modifying schedule because mongoose can't model the schema it's dynamic as well as embedded.

Answer

Mongoose promises use the callback(error, result){} mechanism that follows the exposed crud functions, such as newElement.save( function( err, result){} ). If any error occurs, the promise is rejected, and this is logic.