首页 > 解决方案 > 当字符串超过模型中定义的大小时,如何使 sequelize.js 截断字符串?

问题描述

在我的模型中,我定义了一个大小为 15 的列。

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

输入的字符串是28个字符,我想知道sequelize.js如何自动截断字符串,只剩下15个字符。

目前我收到以下错误:

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

标签: node.jssequelize.js

解决方案


在 Sequelize.js 的配置部分中,没有可以激活截断字符的直接选项。

但是您可以向模型添加验证,包括自定义函数。该文档说明了以下内容:

验证

模型验证,允许您为模型的每个属性指定格式/内容/继承验证。验证在创建、更新和保存时自动运行。您还可以调用 validate() 手动验证实例。


Object.keys(this._changed)创建一个函数,该函数将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);
                    }
                }
            }
        });
    }
}

推荐阅读