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

☆樱花仙子☆ 提交于 2019-12-06 04:13:54

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

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