Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
Bianca A. Avatar asked Oct 20 '25 18:10

Bianca A.


1 Answers

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);
  });
like image 92
Anatol Avatar answered Oct 23 '25 07:10

Anatol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!