身份验证模块“Passport”需要 FindOrCreate 方法才能进行登录。我正在使用 mongoose 以使用以下模式保存我的用户:
var UserSchema = new Schema({
firstname: String,
lastname: String,
email: String,
accounts: []
});
帐户数组包含代表 facebook 帐户的对象,例如{provider: "facebook", uid: "someFacebookId"}
.
我的身份验证策略如下所示:
// Authentication Strategy
passport.use(new FacebookStrategy({
clientID: CONFIG.fb.appId,
clientSecret: CONFIG.fb.appSecret,
callbackURL: CONFIG.fb.callbackURL
},
function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
User.find({ 'accounts.uid': profile.id, 'accounts.provider': 'facebook' }, function(err, olduser) {
if(olduser._id) {
console.log('User: ' + olduser.firstname + ' ' + olduser.lastname + ' found and logged in!');
done(null, olduser);
} else {
var newuser = new User();
var account = {provider: "facebook", uid: profile.id};
newuser.accounts.push(account);
newuser.firstname = profile.name.givenName;
newuser.lastname = profile.name.familyName;
newuser.email = "TBD...";
newuser.save(function(err) {
if(err) { throw err; }
console.log('New user: ' + newuser.firstname + ' ' + newuser.lastname + ' created and logged in!');
done(null, newuser);
});
}
});
});
}
));
问题:查询我的数据库 ( User.find(...)
) 后,回调函数立即执行,无需等待我的数据库回答。这会导致一个未定义的olduser
对象。因此,每次该用户尝试登录时,我都会将同一用户的副本复制到我的数据库中。
如何正确处理此异步回调?