node.js - 使用 Mongoose 模式验证密码/确认密码

标签 node.js mongodb express mongoose

我有一个如下所示的 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
});

到目前为止,我的所有验证都在模式中进行,我想知道如何通过密码验证来实现这一点。用户在两个字段中输入密码,模型应该检查它们是否相同。

这种验证是否属于架构?我是这种验证的新手。

我应该如何验证密码?

最佳答案

我最终发现,您可以使用 virtual pathsinvalidate 函数的组合来实现此目的,如本要点所示,用于匹配的相同目的密码: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);

关于node.js - 使用 Mongoose 模式验证密码/确认密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13982159/

相关文章:

node.js - 使用过滤器进行 Elasticsearch 搜索查询

mongodb - 查找数组中的所有文档 - MongoDB 聚合

node.js - 如何使用 Node.Js 在 MongoDB 中插入或更新数组?

node.js - mongoose.model( 'Foo',FooSchema)与要求( './models/Foos')

node.js - Express app.locals 是否在请求之间共享?

javascript - 如何从路由函数外部获取Nodejs响应对象?

javascript - 如何使用express显示实时变量node.js

javascript - Firebase 身份验证为自定义 token 设置自定义过期时间

javascript - 在 Node.js 上使用 Javascript 运行 selenium

javascript - 使用 MongoDB 和 ExpressJS 的 Elasticsearch 分页