使用promise从mongo db中检索对象时出错
伙计们,我试图用承诺包装下面,并返回一个Mongo文件。
控制器的catch是越来越error: 'TypeError: Cannot call method \'apply\' of undefined'
从数据库返回到控制器的正确方法是什么?
控制器:
Q.fcall(Users.fetchId(authId)).then(function userVerification(userObject) { console.log ('got back',userObject); responses.Unauthorized('Unauthorized ID', res); }).catch(function handleError(err) { responses.InternalServerError(''+err, res); });
用户型号:
Users.prototype.fetchId = function fetchId(authId) { return this.mongodb.fetchId(authId); };
蒙戈:
MongoDatabase.prototype.fetchId = function fetchId(id) { var result = {} return this.authDB.query('users', function(collection) { return collection.findOne({_id:id}, function (err, doc) { if (!_.isEmpty(doc)) { var result = doc; } console.log ('mongo',result); return result; }); }); };
Q.fcall
将函数作为其第一个参数,然后将参数应用于该函数。 通过传递它的Users.fetchId(authId)
,你传递它调用该函数的结果。
尝试传递函数,然后将其应用于它的参数:
Q.fcall(Users.fetchId, authId).then( fn )