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.
Mongoose queries are not promises. They have a . then() function for co and async/await as a convenience.
While save() returns a promise, functions like Mongoose's find() return a Mongoose Query . Mongoose queries are thenables. In other words, queries have a then() function that behaves similarly to the Promise then() function. So you can use queries with promise chaining and async/await.
The problem that Mongoose aims to solve is allowing developers to enforce a specific schema at the application layer. In addition to enforcing a schema, Mongoose also offers a variety of hooks, model validation, and other features aimed at making it easier to work with MongoDB.
Basically, mongoose queries do not return any promise. So that if we want them to queries work like a promise we use the exec function.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With