如何在nodejs中使用sequelize设置模型验证?

时间:2016-02-16 14:35:25

标签: javascript node.js sequelize.js

我是nodejs的新手。我已经使用了nodejs orm的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;
};

错误:

  

可能未处理SequelizeValidationError:验证错误       at /Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/lib/instance-validator.js:149:14       在tryCatch1(/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/util.js:43:21)       在Promise $ _callHandler [as _callHandler](/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:639:13)       在Promise $ _settlePromiseFromHandler [as _settlePromiseFromHandler](/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:653:18)       在Promise $ _settlePromiseAt [as _settlePromiseAt](/Users/esmrkbr/Desktop/nodejs/sequelize-express-demo/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:817:14)       在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 个答案:

答案 0 :(得分:1)

这:

  

可能未处理SequelizeValidationError:

处的验证错误

表示您的续集验证有效。它检查验证并在验证失败时抛出错误(SequelizeValidationError)。

但是这个:

  

可能未处理

表示您对此错误不执行任何操作。您应该捕获此错误并执行某些操作(例如,使用适当的错误代码发送响应)。

例如,当您创建新的“Farmer”时,您的代码可能如下所示:

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)。