2016-02-16 58 views
3

我是nodejs的新手。我已經使用了nodejs orm的sequelize。但我無法設置驗證屬性;如何在nodejs中使用sequelize設置模型驗證?

型號/ farmer.js

'use strict'; 
module.exports = function(sequelize, DataTypes) { 
    var Farmer = sequelize.define('Farmer', { 
    username:{ 
      type: DataTypes.STRING, 
      allowNull: false, 
    }, 
    address: DataTypes.STRING, 
    email: { 
     type: DataTypes.STRING, 
     validate: { 
      isEmail: true 
     } 
    }, 
    phone:{ 
      type: DataTypes.STRING, 
      allowNull: false, 
    }, 
    }, { 
    classMethods: { 
     associate: function(models) { 
      Farmer.hasMany(models.Task); 
     // associations can be defined here 
     } 
    } 
    }); 
    return Farmer; 
}; 

錯誤:

Possibly unhandled SequelizeValidationError: Validation error at /Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/lib/instance-validator.js:149:14 at tryCatch1 (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/util.js:43:21) at Promise$_callHandler [as _callHandler] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:639:13) at Promise$_settlePromiseFromHandler [as _settlePromiseFromHandler] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:653:18) at Promise$_settlePromiseAt [as _settlePromiseAt] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:817:14) at Promise$_settlePromises [as _settlePromises] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:951:14) at Async$_consumeFunctionBuffer [as _consumeFunctionBuffer] (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/async.js:75:12) at Async$consumeFunctionBuffer (/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/async.js:38:14) at doNTCallback0 (node.js:419:9) at process._tickCallback (node.js:348:13)

如何設置驗證模式?

回答

1

此:

Possibly unhandled SequelizeValidationError: Validation error at

意味着你sequelize驗證工作。它檢查驗證和驗證失敗時拋出錯誤(SequelizeValidationError)。

但這:

Possibly unhandled

意味着你什麼都不做,此錯誤。您應該捕獲此錯誤並執行一些操作(例如,使用適當的錯誤代碼發送響應)。

例如,當您創建新的「農民」你的代碼可能是這樣的:

Farmer.create({ 
    //your data 
}).then(function(){ 
    //do something when Farmer is created 
}).catch(function(err){ 
    //do something when you get error 
    //you could check if this is validation error or other error 
}); 

有時它是好主意來驗證外sequelize錯誤(但不sequelize刪除驗證,讓這兩個驗證工作一起)(我寫了一些論據here)。