节点:在我无权访问 req 的函数中访问 req.db

Node: Accessing req.db in a function where I don't have access to req

我正在尝试使用 passport 将 facebook 身份验证添加到我的应用程序 - 这工作正常,但我需要在 passport.use().

内访问数据库

这是我在 routes/auth.js 中的代码:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;

[...]

passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email']
    },
    function(accessToken, refreshToken, profile, cb) {
        var db = need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));

module.exports = router;

app.js中,我有以下代码:

// make our db accessible to the router
app.use(function(req,res,next) {
    req.db = db;
    next();
});

如何在标记的位置访问 auth.js 中的 req.db

如果 dbreq 对象中,您可以配置 FacebookStrategy 以将 req 对象传递给 verify 函数。

参见:

passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email'],
        passReqToCallback: true
    },
    function(req, accessToken, refreshToken, profile, cb) {
        var db = req.db; // need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));

希望有用。