SailsJS-如何在创建记录时指定字符串属性长度而不会出错?

费比扬

我正在使用与MySQL配对的Sails 0.9.8,并想做这样的事情

localhost:1337/player/view/<username of player>

代替

localhost:1337/player/view/<id of player>

因此,我在模型中输入了以下内容:

'username' : {
        type: 'string',
        unique: true,
        minLength: 4,
        maxLength: 32,
        required: true
    },

但是,每当我帆扬帆运行时,我都会出错:

{ [Error: ER_TOO_LONG_KEY: Specified key was too long; max key length is 767 bytes] code: 'ER_TOO_LONG_KEY', index: 0 }

因此,在我遍历模块之后,我发现这是因为默认情况下,Sails在数据库中为string-type属性提供了255的长度。给定的长度可以用'size'覆盖,但是在创建记录时会导致另一个错误。

'username' : {
        type: 'string',
        unique: true,
        minLength: 4,
        maxLength: 32,
        size: 32,
        required: true
    },

创建记录时引起的错误:

Error: Unknown rule: size
at Object.match (<deleted>npm\node_modules\sails\node_modules\waterline\node_modules\anchor\lib\match.js:50:9)
at Anchor.to (<deleted>\npm\node_modules\sails\node_modules\waterline\node_modules\anchor\index.js:76:45)
at <deleted>\npm\node_modules\sails\node_modules\waterline\lib\waterline\core\validations.js:137:33

问题是,如何在创建记录时指定字符串列的大小(以便可以使用唯一键)而不会出错?

木偶

您可以通过类型对象定义自定义验证规则解决此问题具体来说,可以通过定义一个size始终返回true的自定义验证器来解决给定的问题

// api/models/player.js
module.exports = {
  types: {
    size: function() {
       return true;
    }
  },

  attributes: {
    username: {
      type: 'string',
      unique: true,
      minLength: 4,
      maxLength: 32,
      size: 32,
      required: true
    }
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章