有没有人使用nodejs模块'deferred'和'mongoose'?我正在尝试使用deferred.promisify方法来处理mongoose模型的函数,这样我就可以轻松地链接它们,但遇到了一些麻烦。具体来说,我想宣传find
和findById
函数,以便我可以通过ObjectID查找由另一个文档引用的一个文档。
这是我得到的:https://gist.github.com/3321827
然而,这似乎不太理想,因为getAppPermissions
和getApplication
函数似乎只是猫鼬模型的find
和findById
方法的包装器。
我尝试将函数传递给promisify,但是我收到的错误似乎是Object #<Object> has no method '_applyNamedScope'
,因为this
不再绑定到正确的对象。也许我需要使用underscore.bind?有没有人在这方面有任何成功,或者我应该坚持现在的工作?
答案 0 :(得分:2)
您可能没有正确地将上下文传递给方法,正确的方法是直接在Mongoose原型上提供方法的promisified版本:
// I assume that methods you're using are set on mongoose.Model,
// but be sure to check, maybe, they're using some other prototype (!)
var promisify = require('deferred').promisify;
var modelProto = mongoose.Model.prototype;
modelProto.pFind = promisify(modelProto.find);
modelProto.pFindById = promisify(modelProto.findById);
// After that you may use promisified methods directly:
app.get('/apps', requireLogin, function (req, res) {
AppPermissions.pFind({ user: req.user.id, valid: true })
.map(function (permission) {
return ApplicationRecord.pFindById(permission.application)(
function (application) {
application.permission = permisson;
return application;
}
);
}).end(function (applications) {
res.render('applist', { applications: applications });
}, null);
});
您也可以避免污染原型,并间接使用方法:
var promisify = require('deferred').promisify;
var modelProto = mongoose.Model.prototype;
var pFind = promisify(modelProto.find);
var pFindById = promisify(modelProto.findById);
app.get('/apps', requireLogin, function (req, res) {
pFind.call(AppPermissions, { user: req.user.id, valid: true })
.map(function (permission) {
return pFindById.call(ApplicationRecord, permission.application)(
function (application) {
application.permission = permisson;
return application;
}
);
}).end(function (applications) {
res.render('applist', { applications: applications });
}, null);
});
答案 1 :(得分:2)
// I put this in my model file so I didn't have to worry about repeating it
var userProto = mongoose.model('User');
userProto.pFind = deferred.promisify(userProto.find);
userProto.pFindOne = deferred.promisify(userProto.findOne);