在使用Google社交login和护照进行多次查询时执行查询

嗨,大家好,这是我的第一个问题,所以请耐心等待,我有一个问题,使用护照与sequ​​elize,问题发生后,我search数据库的logging,以检查用户是否已经存在,但当护照反序列化,Sequelize执行五个“select查询”,代码类似于我在scotch.io中find的代码,我只是附加了sequelize api:

module.exports = function (passport) { // used to serialize the user for the session passport.serializeUser(function (user, done) { done(null, user.iduser); }); // used to deserialize the user passport.deserializeUser(function (id, done) { userModel.findById(id) .then(function (userVo) { done(null, userVo); }).catch(function(err) { if(err) throw err; }) }); passport.use(new GoogleStrategy({ clientID: 'XXXXX', clientSecret: 'XXXXXX', callbackURL: 'XXXXX' }, function (token, refreshToken, profile, done) { // make the code asynchronous // User.findOne won't fire until we have all our data back from Google process.nextTick(function () { // try to find the user based on their google id sequelize.transaction(function (t) { return sociaLoginModel.findOne({ where: { idprovided: profile.id, logintype: constants.GOOGLE_LOGIN_TYPE } }, { transaction: t }) .then(function (socialLoginResult) { //if user was found, then retrieve and create a session for him returning the value to done var socialLoginVo; if (socialLoginResult) { socialLoginVo = socialLoginResult.dataValues return userModel.findById(socialLoginVo.tb11_fkuser, { transaction: t }) .then(function (userResult) { return userResult.dataValues; }); } else { return individualsModel.create({ name: profile.displayName }, { transaction: t }) .then(function (individualsResult) { var individualsVo = individualsResult.dataValues return userModel.create({ email: profile.emails[0].value, user_type: constants.USER_INDIVIDUALS, tb12_fkindividuals: individualsVo.idindividuals }, { transaction: t }) .catch(function (err) { if (err) throw err; }) .then(function (userResult) { var userVo = userResult.dataValues console.log(typeof profile.id) return sociaLoginModel.create({ idprovided: profile.id, token: token, logintype: constants.GOOGLE_LOGIN_TYPE, tb11_fkuser: userVo.iduser }, { transaction: t }) .then(function (sociaLoginResult) { return userVo }) .catch(function(err) { if(err) throw err; }) }) }).catch(function(err) { if(err) throw err }) } }).catch(function(err) { if(err) throw err }) }).then(function (result) { return done(null, result); }).catch(function (err) { if (err) return done(err) }); }) })) }; 

这段代码在一个文件中,我用它作为app.js中的一个中间件调用:

 require('./logins/google')(passport); 

我用local-login和facebook也是这样做的,就像googlelogin一样,为什么Sequelize正在执行这个查询次数呢? 难道我做错了什么?? 我怎样才能最小化这个数字? 谢谢。

从您的意见,我推断您的快递/护照设置看起来有点类似这样的:

 app.use(passport.initialize()); app.use(passport.session()); app.use(express.static(...)); 

因为Express按顺序调用中间件,这意味着每个请求都会先通过Passport中间件,然后到达静态中间件。

Passport中间件调用passport.deserializeUser(...) ,因此也会调用最终由静态中间件处理的请求(例如,CSS / JS / HTML文件)。

如果重新排列中间件的顺序,那么将首先为这些特定的请求调用静态中间件,并且只有当它不能处理请求时(例如,对于请求应该由你的一个路由处理的请求)到护照中间件:

 app.use(express.static(...)); app.use(passport.initialize()); app.use(passport.session());