Search code examples
mysqlnode.jssails.jswaterline

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


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?


Solution

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