我到处都是文档,但我似乎找不到更新凭据的方法。
这是我通过分析代码能够得到的。
passport.deserializeUser(function(id, done) {
AppUser.findById(id, function(err, user) {
done(err, user);
});
});
DeserializeUser 似乎很有用,但我不确定如何使用它来更新或添加字段?
我试图破解并从登录中复制逻辑并理解它。
passport.use('local-update', new LocalStrategy({
usernameField : 'username',
passReqToCallback : true
},
function(req, username, done) {
console.log(req)
// asynchronous
// AppUser.findOne wont fire unless data is sent back
// process.nextTick(function() {
// // find a user whose email is the same as the forms email
// // we are checking to see if the user trying to login already exists
// AppUser.findOne({ 'local.email' : email }, function(err, user) {
// // if there are any errors, return the error
// if (err)
// return done(err);
// // check to see if theres already a user with that email
// if (!user) {
// //return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
// return done(null, false);
// } else {
// // if there is a user with that email
// // create the username
// var updateUser = new AppUser();
// // set the user's local credentials
// newUser.local.email = email;
// newUser.local.password = newUser.generateHash(password);
// // save the user
// newUser.update(function(err) {
// if (err)
// throw err;
// return done(null, newUser);
// });
// }
// });
// });
}));
然后在表单提交上我这样做了。
app.post('/profile', passport.authenticate('local-update', {
successRedirect : '/', // redirect to the secure profile section
failureRedirect : '/signup' // redirect back to the signup page if there is an error
//failureFlash : true // allow flash messages
}));
这会导致重定向失败。
它不起作用,因为没有响应,但我需要在mongoDB中找到模型。我试图先在控制台中查看 req,这样也许我可以看到如何找到模型,但没有任何显示。
显然上面的 HACKISH 代码,但这是我能做的最好的。我需要一个具体的答案,我确信它很简单,我在文档中错过了它!
编辑:这里的想法是当用户注册/登录时,他们会提供电子邮件。用户登录并创建帐户后,他们可以创建用户名。
编辑:所以我不知道如何用护照提出更新请求,但在我的路由器中我有这样的东西。
app.post('/', function(req, res) {
if (req.user) {
AppUser.findOne({ _id: req.user.id }, function (err, user) {
user.local.username = req.body.username;
user.save(function(err) {
if (err){
console.log('Error')
} else {
console.log('Sucess')
}
});
});
}
});
唯一的问题是浏览器的默认操作,它提交表单并保持页面无休止地重新加载。但它确实更新了我的 mongodb 模型。我必须添加到 Schema,并且必须在我的护照注册逻辑中添加该属性。
但是我可以将这个逻辑添加到我的客户端代码中,然后将 POST 方法放入主干中,这应该可以工作!