JavaScript Promises mongoose and bluebird missing catch and fail JavaScript Promises mongoose and bluebird missing catch and fail mongoose mongoose

JavaScript Promises mongoose and bluebird missing catch and fail


mongoose 4.1+ maintainer suggestion:

es2015 (es6):

require('mongoose').Promise = Promise;

bluebird:

require('mongoose').Promise = require('bluebird');

Q:

require('mongoose').Promise = require('q').Promise;


I do not know moongose, but in general, functions like fail or catch are convenience shortcuts and are not a part of the promises spec. As such the library does not need to have them to be promises-compliant. Apparently in your case they are not there.

You can achieve same functionality with then(successHandler, rejectionHandler).

In order to handle the promise rejection, you can rewrite your code as follows:

User.findOne({ 'email' :  user_email }).exec() }).then (promisedTransformUserSchemaToFrontendObjectWithProjectMapping)   .then (function (feUser) {       return new Promise(function (resolve, reject) {          res.json(feUser);          return resolve(feUser);      });   }).then (undefined, function (err) {      console.log(err);      sendError(res,"failed to get user",err);   });


Another way to do it is shown in the bluebird docs:

https://github.com/petkaantonov/bluebird/blob/master/API.md#promiseresolvedynamic-value---promise

You can wrap the mongoose promise in bluebird's Promise.resolve(), and you will get back a bluebird promise.

 Promise.resolve(User.findOne({ 'email' :  user_email }).exec()) .then (promisedTransformUserSchemaToFrontendObjectWithProjectMapping)   .then (function (feUser) {          res.json(feUser);          return feUser;   }).fail/catch  (function (err) {      console.log(err);      sendError(res,"failed to get user",err);   });