If data found in table then update else insert in sequlizer mysql node js

If data found in table then update else insert in sequlizer mysql node js Update or Insert Functionality
Deepak Sharma
Asked 07-10-2024
9

Answer (1)
In Sequelize, you can achieve the functionality of updating a row if it exists, or inserting a new row if it doesn't exist, using the findOrCreate() method. This method searches for a matching row based on certain criteria and creates a new one if it doesn't exist. If a matching row is found, it can update that row instead. const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'mysql' }); const YourModel = sequelize.define('YourModel', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING, allowNull: false },  });   async function updateOrInsert(dataToUpdateOrInsert) { try { const [row, created] = await YourModel.findOrCreate({ where: { id: dataToUpdateOrInsert.id }, defaults: dataToUpdateOrInsert  }); if (!created) { YourModel.update(dataToUpdateOrInsert, { where: { id: dataToUpdateOrInsert.id } }); } console.log('Operation successful!'); } catch (error) { console.error('Error:', error); } } updateOrInsert({ id: 1, name: 'Updated Name' }); In this example:
  • findOrCreate() searches for a row based on the specified criteria (in this case, id) and returns the row if found along with a boolean flag indicating whether the row was created or not.</li> <li>If the row is found (created is false), update() method is called to update the row with the new data.</li> <li>If the row is not found (created is true), a new row is created with the specified data (dataToUpdateOrInsert).</li> </ul> <xmp> 
Deepak Sharma
Asked 05-04-2024
45 Likes
Comments
Write comment

Submit your answer