使用Mongoose模式validation密码/确认密码

我有一个userSchema ,看起来像这样:

 var userSchema = new Schema({ name: { type: String , required: true , validate: [validators.notEmpty, 'Name is empty'] } , username: { type: String , required: true , validate: [validators.notEmpty, 'Username is empty'] } , email: { type: String , required: true , validate: [ { validator: validators.notEmpty, msg: 'Email is empty' } , { validator: validators.isEmail, msg: 'Invalid email' } ] } , salt: String , hash: String }); 

我所有的validation都在模式中发生,我想知道如何通过密码validation来实现这一点。 用户将密码input到两个字段中,模型应检查它们是否相同。

这种validation属于模式吗? 我是新来的这种validation。

我应该如何validation密码?

我最终发现,您可以使用虚拟pathinvalidate函数的组合来实现这一点,如此要点所示,以达到与密码匹配的目的: https : //gist.github.com/1350041

直接引用:

 CustomerSchema.virtual('password') .get(function() { return this._password; }) .set(function(value) { this._password = value; var salt = bcrypt.gen_salt_sync(12); this.passwordHash = bcrypt.encrypt_sync(value, salt); }); CustomerSchema.virtual('passwordConfirmation') .get(function() { return this._passwordConfirmation; }) .set(function(value) { this._passwordConfirmation = value; }); CustomerSchema.path('passwordHash').validate(function(v) { if (this._password || this._passwordConfirmation) { if (!val.check(this._password).min(6)) { this.invalidate('password', 'must be at least 6 characters.'); } if (this._password !== this._passwordConfirmation) { this.invalidate('passwordConfirmation', 'must match confirmation.'); } } if (this.isNew && !this._password) { this.invalidate('password', 'required'); } }, null); 

我认为密码匹配属于客户端界面,不应该到达服务器(DB层已经太多了)。 用户体验最好不要仅仅通过服务器来告诉用户2个string是不同的。

至于瘦身控制器,胖子模型……所有这些银子弹都应该在原创者身上反击。 任何情况下都没有解决scheme。 在他们自己的情况下考虑每个人。

在这里引入了胖模型的想法,使您使用一个function(模式validation)为完全不同的目的(密码匹配),并使您的应用程序依赖于您现在使用的技术。 有一天,你会想改变技术,你会得到一些没有模式validation的东西…然后你必须记住,你的应用程序的function的一部分依赖于此。 你必须把它移回客户端或控制器。

在使用express-validator之前,它已经下载到./routes/signup.js中的模式级别:

 exports.post = function(req, res){ req.assert('email', 'Enter email').notEmpty().isEmail(); req.assert('username', 'Enter username').notEmpty().isAlphanumeric().len(3,20); req.assert('password', 'Enter password').notEmpty().notContains(' ').len(5,20); res.locals.err = req.validationErrors(true); if ( res.locals.err ) { res.render('signup', { message: { error: 'Woops, looks like we need more info...'} }); return; } ...//save }; 

您可以通过向Schema.methods添加新的函数属性(您也可以使用Schema.statics创buildSchema函数)来将自定义方法附加到模型实例。以下是validation用户密码的示例:

 userSchema.methods.checkPassword = function(password) { return (hash(password) === this.password); }; // You could then check if a user's password is valid like so: UserModel.findOne({ email: 'email@gmail.com' }, function(err, user) { if (user.checkPassword('secretPassword')) { // ... user is legit } }); 

第二validation密码不需要提交注册。 您可能可以逃脱validation在客户端的两个字段是平等的。