Node.js delayed promisify + mongoose

Has anyone worked with nodejs 'offferred' and 'mongoose' modules? I am trying to get a deferred .promisify method to work on the functions of Mongolian models so that I can easily link them, but ran into some problems. In particular, I would like to promise the find and findById , so that I can chain to find one document referenced by another ObjectID document.

Here is what I have: https://gist.github.com/3321827

However, this seems less ideal as the getAppPermissions and getApplication seem a bit larger than the wrappers for the mongoose model's find and findById methods.

I tried just passing functions to promisify, but I get the error Object #<Object> has no method '_applyNamedScope' , which seems to be caused by the fact that this no longer bound to the correct object. Maybe I need to use underscore.bind? Has anyone been successful in this area, or should I just stick to what's working now?

0
source share
2 answers

Mariusz’s answer was pretty close. Here is what ultimately worked for me in this particular case, we hope others can learn from this:

 // I put this in my model file so I didn't have to worry about repeating it var userProto = mongoose.model('User'); userProto.pFind = deferred.promisify(userProto.find); userProto.pFindOne = deferred.promisify(userProto.findOne); 
+2
source

You probably didn’t pass the context correctly to the methods, the right way to do this is to provide promising versions of the methods directly on the prototype of Mongoose:

 // I assume that methods you're using are set on mongoose.Model, // but be sure to check, maybe, they're using some other prototype (!) var promisify = require('deferred').promisify; var modelProto = mongoose.Model.prototype; modelProto.pFind = promisify(modelProto.find); modelProto.pFindById = promisify(modelProto.findById); // After that you may use promisified methods directly: app.get('/apps', requireLogin, function (req, res) { AppPermissions.pFind({ user: req.user.id, valid: true }) .map(function (permission) { return ApplicationRecord.pFindById(permission.application)( function (application) { application.permission = permisson; return application; } ); }).end(function (applications) { res.render('applist', { applications: applications }); }, null); }); 

You can also refrain from contaminating the prototype and use methods indirectly:

 var promisify = require('deferred').promisify; var modelProto = mongoose.Model.prototype; var pFind = promisify(modelProto.find); var pFindById = promisify(modelProto.findById); app.get('/apps', requireLogin, function (req, res) { pFind.call(AppPermissions, { user: req.user.id, valid: true }) .map(function (permission) { return pFindById.call(ApplicationRecord, permission.application)( function (application) { application.permission = permisson; return application; } ); }).end(function (applications) { res.render('applist', { applications: applications }); }, null); }); 
+2
source

All Articles