mongoose and q promises

谁都会走 提交于 2019-12-12 10:47:47

问题


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.


回答1:


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));


来源:https://stackoverflow.com/questions/14088410/mongoose-and-q-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!