How to make sequelize.js truncate the string when it exceeds the size defined in the model?

◇◆丶佛笑我妖孽 提交于 2019-12-08 00:03:45

问题


In my model I have defined a column of size 15.

column: { type: Sequelize.STRING(15), allowNull: false }

The input string is 28 characters, I would like to know how to sequelize.js automatically truncate the string so that only 15 characters remain.

Currently I get the following error:

Unhandled rejection SequelizeDatabaseError: String or binary data would be truncated.

回答1:


In the configuration section of Sequelize.js there is no direct option that can be activated to truncate the characters.

But to the model you can add validations including custom functions. The documentation says the following:

Validations

Model validations, allow you to specify format/content/inheritance validations for each attribute of the model. Validations are automatically run on create, update and save. You can also call validate() to manually validate an instance.


Create a function that will iterate the object that defines which properties changed (Object.keys(this._changed)), then verify that the only data type that could truncate is STRING and finally verify the size of the current string with the maximum allowed thus knowing if it is necessary to shorten the string.

validate: {
    stringTruncate() {
        Object.keys(this._changed).forEach((element) => {
            const temp = this.__proto__.rawAttributes[element];
            if (temp.type.__proto__.__proto__.key == "STRING") {
                if (this[element]) {
                    if (this[element].length > temp.type._length) {
                        this[element] = this[element].substring(0, temp.type._length);
                    }
                }
            }
        });
    }
}



回答2:


You can create a custom setter for that (https://sequelize.readthedocs.io/en/v3/docs/models-definition/#getters-setters)

column: {
  type: Sequelize.STRING(15),
  allowNull: false,
  set: value => value.substring(0, 15)
}


来源:https://stackoverflow.com/questions/53937046/how-to-make-sequelize-js-truncate-the-string-when-it-exceeds-the-size-defined-in

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