Node.js 在Mongoose的自定义回调中使用express response

Node.js 在Mongoose的自定义回调中使用express response,node.js,express,Node.js,Express,我将Mongoose和Firebase与Express一起使用,因为有时我仍然需要继续使用Mongoose的相同回调函数,但参数不同,或者在Firebase回调之后,我想使用一个名为function的自定义回调函数。我的问题是,因为我需要在这个函数中发送响应,所以我需要使用Express回调中的res变量,该变量不可用。那么,如何仍然可以使用Expressres 下面的代码段在userCallback(伪代码)中生成一个运行时错误undefined variable res。我想知道,在这种情况

我将Mongoose和Firebase与Express一起使用,因为有时我仍然需要继续使用Mongoose的相同回调函数,但参数不同,或者在Firebase回调之后,我想使用一个名为function的自定义回调函数。我的问题是,因为我需要在这个函数中发送响应,所以我需要使用Express回调中的
res
变量,该变量不可用。那么,如何仍然可以使用Express
res

下面的代码段在
userCallback
(伪代码)中生成一个运行时错误
undefined variable res
。我想知道,在这种情况下,我怎么能两次使用相同的代码

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
            });
        });
});
当您使用findOne()时,必须使用它的回调(而不是自定义回调),它是

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

您好@Thecave3,我可以和您确认一下,您尝试在userCallback中使用res来响应HTTP请求吗?请问您的userCallback是否是您自己的回调而不是mongoose的标准回调?Hi@CodeCodey,是的,我尝试在userCallback中响应,是的userCallback是我自己的回调,它被传递到mongoose中。
User.findOne({}, (err, document, res){} // Don't think this will work