SailsJS-如何在创建记录时指定字符串属性长度而不会出错? [英] SailsJS - How to specify string attribute length without getting error when creating record?

查看:101
本文介绍了SailsJS-如何在创建记录时指定字符串属性长度而不会出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Sails 0.9.8 paired with MySQL and wanting to do something like this

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

代替

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

所以我在模型中输入了以下内容:

So I put something like this in the model:

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

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

But I've got an error whenever I run sails lift:

{ [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'覆盖,但是在创建记录时会导致另一个错误.

So after I run through the modules, I discovered that it was because by default Sails give string-type attribute a length of 255 in the database. The given length can be overridden with 'size', but it causes another error when creating a record.

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

创建记录时引起的错误:

The error caused when creating a record:

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

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

The question is, how do I specify the size of the string column (so that I can use the unique key) without getting an error when creating a record?

推荐答案

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

You could work around this by defining custom validation rules via the types object. Specifically the given problem could be solved by defining a custom size validator that always returns 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
    }
  }
}

这篇关于SailsJS-如何在创建记录时指定字符串属性长度而不会出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆