Bianca A.
Bianca A.

Reputation: 31

Can't update(nor save) existing row using Sequelize

When trying to .update() or .save() a row I'm getting this error:

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

I tried all 4 ways the docs uses as examples(with and without defining the attributes I wanna save), nothing worked. This is my actual code for updating:

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

And this is the guild model:

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

What am I missing here?

Upvotes: 3

Views: 2078

Answers (2)

Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

I had the same problem. It occurs when you specify the attributes you want to fetch from the database without including the primary key in the attributes. And when you attempt to save, it will throw the following error:

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

So the simple solution is to include the primary key in the attributes like this:

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

Upvotes: 4

Bianca A.
Bianca A.

Reputation: 31

Ok, so the problem seems that was the attributes: ['guildLocale'] in the .findOrCreate() method. I can't tell why, to be honest, gonna read that doc again to be sure, but I'll leave this answer if another newbie is getting trouble with this, ;P...

Upvotes: 0

Related Questions