0

I'm using MySQL for the first time through a NodeJS application. I'm managing to insert into a table, but I'm attempting to adapt my code to upsert the data instead, if a value matches. I've been trying to incorporate "ON DUPLICATE KEY UPDATE", but instead my data is getting inserted twice.

Within the NodeJS application, the mysql version is 2.18.1

My data is structured in an array of objects, like below:

const data = [
 {staffId: 12345, name : "John Doe", age: 40},
 {staffId: 67890, name : "Michael Jordan", age: 45},
 {staffId: 33333, name : "Jane Doe", age: 50},
]

Below is the code I've been using for a plain old insert, which is working as intended:

    const connection = await mysql.createConnection({
      host: "xxxxx",
      user: "xxxxx",
      password: "xxxxx",
      database: "xxxxxx",
      multipleStatements: true,
    });

let query = "";

 data.forEach((item) => {
    query += mysql.format("REPLACE INTO staff_data SET ?", item);
    query += ";"
  });

  await connection.query(query);

How can I adapt this so that if a duplicate staffId is passed, the row is updated rather than creating a new table row?

I have tried adding in the below line, into the loop (after the initial mysql.format method):

query += mysql.format(" ON DUPLICATE KEY UPDATE ?", {staffId: item.staffId})

Any help would be great. MySQL is confusing coming from a background of MongoDB!

Thanks

edit: I've tried updating an age using the below query but I get a syntax error. I also tried using the INSERT keyword instead of replace.

REPLACE INTO staff_data VALUES `staffId` = 12345, `name` = ‘John Doe’, `age` = ‘60’,  ON DUPLICATE KEY UPDATE staffId = VALUES(‘staffId’);
8
  • Use ON DUPLICATE KEY UPDATE staffid = NEW.staffid (or before MySQL 8, staffid = VALUES(staffid))
    – Barmar
    Commented Jun 26 at 16:19
  • @Barmar it throws an error when I try to add: query += mysql.format(` ON DUPLICATE KEY UPDATE staffId=VALUES(${item.staffId})` Is that what you meant by your comment? Commented Jun 26 at 16:34
  • It shouldn't be ${item.staffId}, just staffid. VALUES(columnname) means to use the value that would have been inserted it not for the duplicate.
    – Barmar
    Commented Jun 26 at 16:35
  • The update query I'm using now looks like this, and is throwing an error still sadly: ``` REPLACE INTO staff_data VALUES staffId = 12345, name = ‘John Doe’, age = ‘60’, ON DUPLICATE KEY UPDATE staffId = VALUES(‘staffId’);``` Commented Jun 26 at 16:46
  • REPLACE doesn't use ON DUPLICATE KEY.
    – Barmar
    Commented Jun 26 at 16:47

0

Browse other questions tagged or ask your own question.