我试图在一个旧项目上实现passsport,并且scema被设置为嵌套用于不同的东西,例如下面的名称模式是我的子模式。(还有更多这只是一个例子)
var nameSchema = new Schema(
{
_id: false,
"firstname" : {type: String, required: true},
"lastname" : {type: String, required: true}
});
// Schema setup
var schema = new Schema(
{
local :
{
name : nameSchema,
email : { type: String, required: true, trim: true, unique: true, select: true},
password : { type: String, required: true, trim: true, select: true},
regDate : { type: Date, select: false, createdAt: true},
alevel : { type: Number, min : 1, max : 5, default: 1, select: true },
}
});
但是当我把它添加到我的本地策略时,我得到一个错误TypeError: Cannot set property 'firstname' of undefined
如何实现嵌套的json策略。
目前我所拥有的是:
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
aLevelField : 'aLevel',
namefield : {
firstnameField : 'firstname',
lastnameField : 'lastname'
},
passReqToCallback : true
},
function(req, email, password, done) {
process.nextTick(function() {
User.findOne({ 'local.email' : email }, function(err, user) {
if (err){
return done(err);
}
if (user){
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
var user = new User();
user.local.email = email;
user.local.password = password;
user.local.aLevel = req.body.aLevel;
user.local.name.firstname = req.body.firstname; // <-- error
user.local.name.lastname = req.body.lastname;
console.log('after define',user);
user.save(function(err){
if (err){
console.log(err)
throw err;
}
return done(null, user);
});
}
});
});
}));
答案 0 :(得分:0)
只是因为任何人都会碰到这个并且无法弄明白。当我打电话给
user.local.name.firstname = req.body.firstname
我可以假设这是试图访问.name.firstname
,但因为它是空的,所以也没有设置.firstname
。
要解决它:
user.local.name = {
firstname : req.body.firstname,
lastname : req.body.lastname
};