如何处理asynchronous。 findOrCreate护照和mongoose的方法
身份validation模块“Passport”需要FindOrCreate方法才能进行login。 我正在使用mongoose为了保存我的用户以下模式:
var UserSchema = new Schema({ firstname: String, lastname: String, email: String, accounts: [] });
accounts数组包含代表Facebook帐户的对象,如{provider: "facebook", uid: "someFacebookId"}
。
我的身份validation策略如下所示:
// 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(...)
)后,立即执行callback函数,而不用等待我的数据库回答。 这导致一个未定义的olduser
对象。 因此,每当此用户尝试login时,我都会将同一用户的dublicatejoin到我的数据库中。
如何正确处理这个asynchronouscallback?
User.find
返回一组符合条件的文档。 在你的情况下,你想要使用User.findOne
,然后检查if (olduser)...
以确定是否find匹配的文档。
讨厌挑剔,但这里提到的其他方法会打破,如果两个用户同时尝试注册 – 在您投入生产之前,您需要查看事务: http : //www.mongodb.org/显示/ DOCS /两相+提交
process.nextTick(function () { var query = User.findOne({ 'fbId': profile.id }); query.exec(function (err, oldUser) { console.log(oldUser); if(oldUser) { console.log('User: ' + oldUser.name + ' found and logged in!'); done(null, oldUser); } else { var newUser = new User(); newUser.fbId = profile.id; newUser.name = profile.displayName; newUser.email = profile.emails[0].value; newUser.save(function(err) { if(err) {throw err;} console.log('New user: ' + newUser.name + ' created and logged in!'); done(null, newUser); }); } }); });
有一个应用程序: mongoose-findorcreate
- Nodejs:用户信息/数据库和authentication(Passport)
- 正确的方式来结合使用loopback.js路由和APIvalidation
- 我们如何在node.js中使用Firebase Auth创build用户?
- Firebase 3 node.js服务器authentication是否会改变?
- 什么是sails.js最好的authentication方法?
- JWT身份validation:使用UI令牌来validation石墨烯/ Django(GraphQL)查询?
- firebase.auth()。createUserWithEmailAndPassword Undefined不是一个函数
- 节点 – Passport Auth – Authed Post路由在表单提交时挂起
- 未知的身份validation策略护照