【问题标题】:How to make a field required in Sequelize?如何在 Sequelize 中设置必填字段?
【发布时间】:2018-01-06 00:29:08
【问题描述】:

假设我想在 sequelize 中设置 firstname 字段,在 mongoose 中我可以只说 required: true 在该字段上,但我如何在 Sequelize 中做到这一点?

【问题讨论】:

    标签: mysql node.js postgresql sequelize.js


    【解决方案1】:

    如果您使用的是 Sequelize,则 mongoose 上的 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)
    });
    

    参考资料:

    【讨论】:

    • 如何设置,比如“[Fieldname] 是必​​需的?”必填字段的消息?
    【解决方案2】:

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

    foo: {
      type: Sequelize.STRING,
      allowNull: false,
      validate: {
        notNull: { msg: "foo is required" },
      },
    }
    

    更多信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多