【问题标题】:Waterline UUID type and validationWaterline UUID 类型和验证
【发布时间】:2015-01-02 02:44:56
【问题描述】:

我想创建一个以 uuid 字段作为主键的“客户”模型。这似乎很简单,但事实并非如此,因为 Waterline 不包含任何本机验证器。

如何编辑此代码,以便我可以将 uuid 作为此模型的唯一主键?

module.exports = {
  identity: 'customer',
  connection: 'mysql',
  attributes: {
    // Properties
    uuid: {
      type: 'string',
      primaryKey: true,
      unique: true,
      index: true,
      uuidv4: true,
    },
    firstName: {
      type: 'string',
    },
    // …
  }
};

非常感谢。

【问题讨论】:

    标签: validation model sails.js uuid waterline


    【解决方案1】:

    我正在寻找方法来做完全相同的事情并找到了两种方法。

    1. 通过使用像node-uuid这样的包

      var uuid = require('node-uuid');
      

      ,然后在模型中

      autoPK: false,
      
      attributes: {
          uuid: {
              type: 'string',
              primaryKey: true,
              defaultsTo: function (){ return uuid.v4(); },
              unique: true,
              index: true,
              uuidv4: true
          },
          // ...
      }
      

      将autoPK设置为false是为了防止水线自动生成id。

      参考:Feature Request: GUIDs as Primary Keys

    2. 通过使用像node-uuidbeforeCreate这样的包

      var uuid = require('node-uuid');
      

      ,然后在模型中

      autoPK: false,
      
      attributes: {
          uuid: {
              type: 'string',
              primaryKey: true,
              unique: true,
              index: true,
              uuidv4: true
          },
          // ...
      },
      
      beforeValidate: function(values, next) {
          values.uuid = uuid.v4();
          next();
      }
      

      参考:

    我更喜欢第一个,因为它更简单,但这取决于。

    希望这会有所帮助。

    【讨论】:

    • 我尝试了两种基于 n​​ode-uuid 的解决方案。我有一个用 100 条测试记录填充我的数据库的函数。只插入第一个,因为下一个生成的 uuid 发生冲突。我不明白为什么。
    • @mastergap 可能是因为您在模型中生成了一个 uuid 作为默认值,而不是使其成为由水线执行以生成默认值的函数。
    • “uuidv4”是否在文档中不明显?我找不到它。
    • 另外,您说“beforeCreate”,然后执行“beforeValidate”。哪一个更适合,在这里?
    • 请更新它,因为 node-uuid 已被弃用 github.com/kelektiv/node-uuid
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2014-10-26
    • 2015-09-20
    • 1970-01-01
    • 2013-12-21
    • 2020-05-20
    相关资源
    最近更新 更多