在 Sails Mongo 块 beforeCreate 中将密码字段设置为 'required'

Setting password field to 'required' in Sails Mongo blocks beforeCreate

我的 API 使用 SailsJs 和 MongoDb。对于用户创建,我使用 beforeCreate lifecycle callback 到 运行 bcrypt 来散列我的密码字段。

我遇到了这个奇怪的错误,其中如果我将我的 encrPassword 字段设置为

{required : true}

我的代码 stops 工作并发出以下错误:

 {
  "error": "E_VALIDATION",
  "status": 400,
  "summary": "1 attribute is invalid",
  "model": "User",
  "invalidAttributes": {
    "encrPassword": [
      {
        "rule": "string",
        "message": "Value should be a string (instead of null, which is an object)"
      },
      {
        "rule": "required",
        "message": "\"required\" validation rule failed for input: null\nSpecifically, it threw an error.  Details:\n undefined"
      }
    ]
  }

这是我的代码示例:

attributes: {
    fullname : {type : 'string'},
    username : {type : 'string', unique:true, required:true},
    encrPassword : {type : 'string'}, // ==> this works
    // encrPassword : {type : 'string', required:true}, ==> this doesn't
},

insert : function(req, cb){
    console.log('Insert ', req);
    if(typeof req.fullName == 'string' && typeof req.username == 'string'){
        User.findOne({username : req.username}).exec(function(err, res){
            if(!res){
                User.create(req).exec(function(err, resp){
                    console.log('create', null, resp);
                    if(err)
                      cb(err);
                    else cb(null, resp);
                });
            }
            else cb({message: 'already eists'})
        });
    }
    else cb({message: 'Bad Request'});
},

beforeCreate : function(req, next){
    console.log('In bcrypt');
    bcrypt.genSalt(10, function(err, salt){
        if(err) return next(err);
        bcrypt.hash(req.password, salt, function(err, hash){
            if(err) return next(err);
            req.encrPassword = hash;
            delete req.password;
            console.log('Leaving BCrypt'); 
            next();
        });
    });
}

ps。我严格检查错别字;上述示例中的任何拼写错误或语法错误都是编辑隐藏我不想分享的任何代码的结果

在调用 beforeCreate 之前完成验证。
当时没有 encrPassword,因此出现错误。