2015-06-19 85 views
0

我敢肯定,問題是與密碼驗證程序,因爲如果我註釋掉文檔插入。另外如果我輸入一個有效的密碼一切正常。這裏是我的整個UserSchema貓鼬得到模型驗證失敗,而不是自定義錯誤消息

var UserSchema = new Schema({ 
    firstName: String, 
    lastName: String, 
    email: { 
     type: String, 
     unique: true, 
     match: /.+\@.+\..+/ 
    }, 
    website: { 
     type: String, 
     set: urlModifier 
    }, 
    username: { 
     type: String, 
     trim: true, 
     required: true, 
     unique: true 
    }, 
    password: { 
     type: String, 
     validate: [ 
      function(password) { 
      return password.length >= 6; 
      }, 
     'Password should be longer' 
    ] 
    }, 
    createdAt: { 
     type: Date, 
     default: Date.now 
    }, 
    role: { 
     type: String, 
     enum: ['admin', 'owner', 'user'] 
    } 
}); 

我有這個問題是不是我的自定義錯誤消息我得到

ValidationError: User validation failed 
<br> &nbsp; &nbsp;at model.Document.invalidate (C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\document.js:1162:32) 
    <br> &nbsp; &nbsp;at C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\document.js:1037:16 
     <br> &nbsp; &nbsp;at validate (C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\schematype.js:651:7) 
      <br> &nbsp; &nbsp;at C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\schematype.js:679:9 
       <br> &nbsp; &nbsp;at Array.forEach (native) 
        <br> &nbsp; &nbsp;at SchemaString.SchemaType.doValidate (C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\schematype.js:656:19) 
         <br> &nbsp; &nbsp;at C:\Users\lotus\Desktop\mastering_mean\application\node_modules\mongoose\lib\document.js:1035:9 
          <br> &nbsp; &nbsp;at process._tickCallback (node.js:355:11) 

貓鼬版^ 4.05

不知道這是一個錯誤,API改變了,或者我做錯了什麼。

回答

0

在我學習的特定教程中沒有提到這一點。

http://mongoosejs.com/docs/validation.html

定製錯誤消息是在驗證錯誤對象可用返回到在控制器和err保存(ERR)函數。

基本

user.save(函數(ERR){ 如果(ERR){ 未來回報(ERR); }其他{ res.json(用戶);} });

將返回默認的錯誤消息 「用戶驗證失敗」

user.save(function(err) { 
     if(err) { 
      console.log(err.errors.password.message); 
      return next(err); 
     } else { 
      res.json(user); 
     } 
    }); 

將返回的自定義錯誤消息