无法使用Sequelize更新(或保存)现有行

时间:2018-10-08 12:46:19

标签: javascript node.js sqlite sequelize.js

尝试连续.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'});

我在这里想念什么?

2 个答案:

答案 0 :(得分:0)

好的,所以问题似乎是,它是attributes: ['guildLocale']方法中的.findOrCreate()。坦率地说,我无法确定为什么要再次阅读该文档以确保确定,但是如果另一个新手对此有麻烦,我会留下这个答案; P ...

答案 1 :(得分:0)

我遇到了同样的问题。当您指定要从数据库中获取的属性而不在属性中包含主键时,就会发生这种情况。当你尝试保存时,它会抛出以下错误:

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