2017-07-06 48 views
0

我的API使用SailsJs和MongoDb。對於用戶創建,我使用beforeCreate lifecycle callback來運行bcrypt以哈希我的密碼字段。在創建風帆Mongo塊之前將密碼字段設置爲'required'

我遇到這個奇怪的錯誤,其中,如果我我encrPassword字段設置爲

{required : true} 

我的代碼停止工作,併發出以下錯誤:

{ 
    "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。我嚴格檢查錯別字;上述示例中的任何拼寫錯誤或語法錯誤都是編輯隱藏我不想分享的任何代碼的結果

回答

1

驗證在致電beforeCreate之前完成。
當時沒有encrPassword,因此是錯誤。

相關問題