SailsJS - How to specify string attribute length without getting error when creating record?

浪尽此生 提交于 2019-12-30 06:51:25

问题


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

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

instead of

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 }

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?


回答1:


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
    }
  }
}



回答2:


The marked answer is quiet old. As per the latest sails version (1.0.2 as of the date of writing this answer),

I used the columnType attribute like this:

attributes: {

  longDescription: {
    type: 'string',
    columnType: 'text'
  }
}


来源:https://stackoverflow.com/questions/21359455/sailsjs-how-to-specify-string-attribute-length-without-getting-error-when-crea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!