Mongoose and q promises

I am working with the mongoose / q promises sample framework here , but it seems that there are some problems with nfbind when trying to use findOne, mainly because the samples from the Q framework do not seem to match what is specified in the gist.

My code is:

var mongoose = require('mongoose'); var Q = require('q'); var user_schema = mongoose.Schema({username:String, last_touched:Date, app_ids:[String]}); var user = mongoose.model('user', user_schema); exports.user = user; exports.user.find = Q.nfbind(user.find); exports.user.findOne = Q.nfbind(user.findOne); 

If I call user.findOne({username:'test'}).then(function(err, user) { ... } , the user is always undefined. If I delete the export and use the version without lunch with callbacks, I get the user I miss some special magic, but looking at the code implementation, an example from Q github and from the mongoose demo ... Nothing jumps out. Any ideas on how I can get findOne to work with Q?

I also tried to install the nfbind functions in the source, not in the module, but to no avail.

+6
source share
1 answer

Since the methods that you nfbinding are methods of the user object, you need to bind them to this object before passing them to nfbind so that the this pointer is saved when called.

This approach worked for me:

 exports.user.find = Q.nfbind(user.find.bind(user)); exports.user.findOne = Q.nfbind(user.findOne.bind(user)); 
+5
source

All Articles