javascript - 无法使用 Sequelize 更新(或保存)现有行
问题描述
当尝试.update()
或.save()
一行时,我收到此错误:
Unhandled rejection Error: You attempted to save an instance with no primary key,
this is not allowed since it would result in a global update
我尝试了文档用作示例的所有 4 种方法(有和没有定义我要保存的属性),但没有任何效果。这是我用于更新的实际代码:
Sydney.databases.guilds.findOrCreate({
attributes: ['guildLocale'],
where: {
guildID: _guild.id,
},
defaults: {
guildID: _guild.id,
guildLocale: 'en_US',
guildPrefix: '?',
},
}).spread((guild, created) => {
guild.update({guildLocale: args[1]})
.then(() => console.log(7))
.catch((e) => throw e);
});
这是公会模型:
let model = sequelize.define('guild', {
guildID: {
field: 'guild_id',
type: DataTypes.STRING,
primaryKey: true,
},
guildLocale: {
field: 'guild_locale',
type: DataTypes.STRING,
},
guildPrefix: {
field: 'guild_prefix',
type: DataTypes.STRING,
},
}, {tableName: 'guilds'});
我在这里想念什么?
解决方案
我有同样的问题。当您指定要从数据库中获取的属性而不包括属性中的主键时,就会发生这种情况。当您尝试保存时,它会抛出以下错误:
Unhandled rejection Error: You attempted to save an instance with no primary key, this is not allowed since it would result in a global update
所以简单的解决方案是在属性中包含主键,如下所示:
Sydney.databases.guilds.findOrCreate({
attributes: ['guildLocale', 'guildID'], // include guideID here!!
where: {
guildID: _guild.id,
},
defaults: {
guildID: _guild.id,
guildLocale: 'en_US',
guildPrefix: '?',
},
}).spread((guild, created) => {
guild.update({guildLocale: args[1]})
.then(() => console.log(7))
.catch((e) => throw e);
});
推荐阅读
- javascript - 如何使用 JQuery 制作显示动态图像放大版本的弹出框?
- visual-studio - 是否还有适用于 Visual Studio 2013 Update 5 的有效 Web 安装程序?
- javascript - e.preventDefault() 不是 Reactjs 中的函数,使用了绑定
- r - 如何跨两个不同的数据框列表进行计算?
- javascript - 同时启用 redux-promise 和 redux-saga 中间件似乎会导致问题
- javascript - 在不刷新页面的情况下显示更改的 localStorage?
- ios - SwiftUI List 仅使用给定数组的第一项
- python - 如果第一行中的字符串符合标准,第二行符合其他标准,则
- azure - 我们是否可以更改 Azure 门户中的设置,以便在 Azure ASR 中故障转移后创建的 VM 具有高级磁盘类型?
- c# - 如何将多行文本添加到 ListBox 项?