我是Web开发的新手。
我正在关注Node,Express,Passport和MongoDB tutorial(关于SO的此特定教程存在疑问,但我无法将解决方案应用于我的问题。)
护照规定保存电子邮件和密码。我想添加一个displayName。我已将此属性添加到架构中。在注册表单中为其添加了一个字段。然后尝试在创建新用户时通过localStrategy保存它。电子邮件和密码保存成功,但是displayName失败。
在user.js中,userSchema定义为
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
displayName : String,
}
});
module.exports = mongoose.model('User', userSchema);
注册表单在signup.ejs中
<form action="/signup" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="displayName">
//I want to save this to local.displayName in userSchema
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Signup</button>
</form>
routes.js处理注册表单
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
passport.js
passport.use('local-signup', new LocalStrategy({
//by default, local strategy uses username and password, we will override
//with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req,displayName,email,password, done) {
//asynchronous
//User.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
User.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.'));
} else {
//if there is no user with that email
//create the user
var newUser = new User();
//set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// i need help with this.
newUser.local.displayName = req.body.displayName;
//save the user
newUser.save(function(err) {
if(err)
throw err;
return done(null, newUser);
});
}
});
});
}));
我想在注册时将为displayName输入的值以表格的形式保存到local.displayName。
我尝试过:
newUser.local.displayName = req.body.displayName;没用
还
var displayName = req.body.displayName;没用
我尝试了以下解决方案,但无济于事:
Using PassportJS, how does one pass additional form fields to the local authentication strategy?
how can i store other form fields with passport-local.js
Update or add fields in passport.js local-strategy?
编辑:req.body.displayName和newUser.local.displayName的console.log输出
答案 0 :(得分:0)
好吧,事实证明它从一开始就在工作。我使用Robo 3T来查看数据库内部,刷新连接不足以反映更改。与主机重新建立连接后,我可以看到更新的数据库。