Reputation: 1756
I'm working from the mongoose/q promises framework sample here, but seem to have some issues with the nfbind when trying to use findOne, mainly since the samples from the Q framework don't seem to match those in the gist.
My code:
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 remove the export and use the non-promise version with callbacks, I get the user. I'm missing some special magic, but after looking at the code implementation, the example on from the Q github, and from the mongoose demo... Nothing really jumps out. Any ideas as to how I get to make a findOne
work with Q?
I have also tried to set the nfbind
functions up in the source rather than in the module, but to no avail.
Upvotes: 6
Views: 4756
Reputation: 311955
Because the methods you're nfbinding are methods of the user
object, you need to bind
them to that object before passing them to nfbind
so that the this
pointer is preserved 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));
Upvotes: 5