Jacky Chiu Jacky Chiu - 1 year ago 235
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';
}).catch((err) => {

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

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

Any help would be appreciated.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download