Folks, I am trying to wrap the following with promises, and return a Mongo document.
Controller's catch is getting error: 'TypeError: Cannot call method \'apply\' of undefined'
What is the proper way to return the Object from the db to the controller?
Controller:
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 Model:
Users.prototype.fetchId = function fetchId(authId) {
return this.mongodb.fetchId(authId);
};
Mongo:
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
takes a function as its first parameter, and then arguments to apply to that function. By passing it Users.fetchId(authId)
, you're passing it the result of calling that function.
Try passing the function, and then the arguments you want to apply to it:
Q.fcall(Users.fetchId, authId).then( fn )