Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose and q promises

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.

like image 808
mlaccetti Avatar asked Dec 30 '12 04:12

mlaccetti


People also ask

Are Mongoose queries promises?

Mongoose queries are not promises. They have a . then() function for co and async/await as a convenience.

Does Mongoose find return a Promise?

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.

What problem does Mongoose solve?

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.

Why exec () is used in Mongoose?

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.


1 Answers

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));
like image 75
JohnnyHK Avatar answered Sep 29 '22 23:09

JohnnyHK