如何处理异步。护照和猫鼬findOrCreate方法 [英] How to deal with async. findOrCreate method for passport and mongoose
问题描述
身份验证模块的'护照'需要为了做一个登录一个FindOrCreate方法。我使用的猫鼬为了我的用户保存以下模式:
Authentication module 'Passport' requires a FindOrCreate method in order to do a login. I am using mongoose in order to save my users with the following schema:
var UserSchema = new Schema({
firstname: String,
lastname: String,
email: String,
accounts: []
});
账目阵认为,重新present Facebook账户,状物体 {提供商:脸谱,发表于:someFacebookId}
我的认证策略是这样的:
My authentication strategy looks like this:
// 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
对象。所以,我收到同一用户的dublicate到我的数据库每到这个用户尝试登录的时间。
Problem: After querying my database (User.find(...)
) the callback function is executed immediately without waiting for my database to answer. This results in a undefined olduser
object. So I am getting a dublicate of the same user into my database every time this user tries to login.
我如何妥善处理这一异步回调?
How do I handle this asynchronous callback properly?
推荐答案
User.find
返回的阵列的匹配条件的文件的。你的情况,你要使用 User.findOne
代替,然后检查如果(olduser)...
确定如果匹配的文档被发现。
User.find
returns an array of documents that match your conditions. In your case you want to use User.findOne
instead, and then check if (olduser)...
to determine if a matching doc was found.
这篇关于如何处理异步。护照和猫鼬findOrCreate方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!