如何在Sequelize中创建一个字段?

Dak*_*ani 4 mysql postgresql node.js sequelize.js

假设我想在sequelize中创建firstname字段,在mongoose中我只能说必需:在该字段上为true但是我如何在Sequelize中执行此操作?

joa*_*olo 14

如果您使用Sequelize,相当于required: true对猫鼬就是allowNull: false.你会沿着这些方向写一些东西:

const YourTable = sequelize.define('your_table', {
  firstname: {
    type: Sequelize.STRING,

    // This will require the firstname be present
    allowNull: false,

    // If you want to also have a length restriction, add the next line
    len: [2,50], // only allow values with length between 2 and 50
       // That is 'Al' will be accepted and so will 'Rigoberto Fernando Luis María'. 
       // But '' or 'J' won't be good enough

     // If you use sequelize transforms, this will remove spaces on both ends
     // of the string also
     trim: true,
  },
  // All the other fields (columns)
});
Run Code Online (Sandbox Code Playgroud)

参考文献:


小智 5

回答 Dmitry 问题:您可以在字段定义下定义自定义验证错误:

foo: {
  type: Sequelize.STRING,
  allowNull: false,
  validate: {
    notNull: { msg: "foo is required" },
  },
}
Run Code Online (Sandbox Code Playgroud)

更多信息在这里