Reputation: 797
I am using Mongoose and Firebase along with Express and since sometime I have to still go on with the same callback function of mongoose but with different parameters or after a firebase callback I was thinking of use a custom callback named function. My issue is that since I need to send a response in this function I need to use the res
variable from the Express callback which is not available. So how can still use the Express res
?
This snippet below generates a run time error of undefined variable res
into userCallback
(pseudocode). I wonder how can I use the same code twice in situations like this one?
function userCallback(err, user) {
// some other processing
res.json({});
}
router.get('/:username', function (req, res, next) {
let idToken = req.header('idToken');
admin.auth().verifyIdToken(idToken, true)
.then(function (decodedToken) {
let email = req.query.email;
if (!email) {
User.findOne({
username: req.params.username
}, userCallback);
} else {
admin.auth().getUserByEmail(req.params.username).then((user_firebase) => {
User.findOne({
uid: user_firebase.uid
}, userCallback);
}).catch((error) => {
res.json({
result: false,
error
});
});
}
}).catch(function (error) {
res.json({
result: false,
error
});
});
});
Upvotes: 0
Views: 91
Reputation: 116
When you are using findOne(), you have to use its callback (not your customized callback) which is
User.findOne({<search_params>}, (err, document)=>{
// this callback is specific to mongoose API and you have to follow the parameters
// err is the error occurred when running findOne()
// document is returned document passed back to you by findOne()
// when your customized callback uses res, it had no knowledge of it in its current scope
})
The reason why you are unable to return the res is because the res was not passed into your customized callback as a parameter. Thus your custom callback does not know res exists! I suggest you handle the response at function(decodeToken) level instead / you could try passing res into your callback as the last parameter see if it helps.
User.findOne({}, (err, document, res){} // Don't think this will work
Upvotes: 1