node.js - 当字符串超过模型中定义的大小时,如何使 sequelize.js 截断字符串?
问题描述
在我的模型中,我定义了一个大小为 15 的列。
column: { type: Sequelize.STRING(15), allowNull: false }
输入的字符串是28个字符,我想知道sequelize.js如何自动截断字符串,只剩下15个字符。
目前我收到以下错误:
Unhandled rejection SequelizeDatabaseError: String or binary data would be truncated.
解决方案
在 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);
}
}
}
});
}
}
推荐阅读
- node.js - 使用 Docker 部署 Nuxt,未注册环境变量和意外的 API 调用?
- javascript - 为什么关心覆盖 hasOwnProperty 而不是其他 Object.prototype 方法?
- javascript - 使用 puppeteer browserWSEndpoint 上传文件
- makefile - Make:通配符匹配完整路径?
- javascript - 有没有办法从对象生成新的 HTML 元素?
- python-3.x - 如何等待 CodePipeline 在 Cloudformation 中部署功能
- model - 在 Google AutoML 翻译中使用带有自定义模型的词汇表
- php - 有没有办法从 2 个不同的表单中插入数据并插入到列中的 1 行中?
- terraform - Terraform 模块抛出关于需要字符串的错误
- swift - SwiftUI 将 View 存储为变量,同时传递一些绑定