UPDATE Data in Sequelize Tutorial

Welcome to this detailed tutorial on updating data in Sequelize! Just as you learned how to insert and select data, updating records is an essential part of CRUD operations. Think of updating data like editing a document – you retrieve the current version, make your changes, and then save the updated version back. In this lesson, we will cover how to update a single record, update multiple records at once, and even update records within seeder files.

Recalling the SQL UPDATE Statement

In raw SQL, the UPDATE statement allows you to change existing records. For example, imagine a table called birds that lists different bird species and their coordinates. If you discover that the longitude for "Great Blue Heron" is incorrect, you might run:

UPDATE birds
SET longitude = 81.623863
WHERE species = "Great Blue Heron";
  

This command changes the longitude for the record with species "Great Blue Heron" and is the basic idea behind updating data.

Updating a Single Record in Sequelize

In Sequelize, updating data is done in a similar fashion by first retrieving the record, modifying the fields, and then saving the changes back to the database. Imagine you are editing a profile on a social media app. You load your profile, update your bio, and then click "save" to persist the changes.

Here’s how you can update a single record using the find-update-save approach:

// Find the record for "Great Blue Heron"
const greatBlueHeron = await Bird.findOne({ where: { species: "Great Blue Heron" } });

// Change a single attribute by re-assigning its value
greatBlueHeron.longitude = 81.623863;

// Save the changes to the database
await greatBlueHeron.save();
  

In this example, the record is only updated in the database once the save() method is called. Prior to that, any changes exist only in the instance.

Updating Multiple Attributes in a Single Record

You can also update multiple attributes at once by using the set() method. Think of it like editing several fields on a form before saving:

// Retrieve the record that needs updating
const greatBlueHeron = await Bird.findOne({ where: { species: "Great Blue Heron" } });

// Update multiple fields at once using set
greatBlueHeron.set({
  longitude: 81.623863,
  latitude: 58.936047
});

// Save the updated record to the database
await greatBlueHeron.save();
  

This approach is useful when you need to change several columns at once without making multiple calls to update each one separately.

Using the Instance.update Method for More Control

If you need more precise control over which attributes get updated, you can use the update() method on the instance. This method will both update the instance in memory and save only the specified changes to the database. For example:

// Find the record
const greatBlueHeron = await Bird.findOne({ where: { species: "Great Blue Heron" } });

// Change the species locally
greatBlueHeron.set({ species: "GBH" });

// Update only the longitude and latitude in the database
await greatBlueHeron.update({
  longitude: 81.623863,
  latitude: 58.936047
});
  

In this scenario, even though the instance has a changed species, only the latitude and longitude will be saved to the database.

Updating Multiple Records at Once

Sometimes you need to update more than one record at a time. For instance, if you find that two species were observed at the same location, you can update their coordinates in a single command. This is done by using the Model.update method on the model itself.

const { Op } = require('sequelize');

// Update the latitude and longitude for two specific records
await Bird.update(
  { latitude: 70.0000, longitude: 130.333333 },
  { where: { id: { [Op.or]: [1, 2] } } }
);
  

This command updates the records where the id is either 1 or 2. Notice that using the where clause carefully is crucial, because leaving it out would update every record in the table!

Updating Records in Seeder Files

Just as you can insert seed data into your database, you can also perform bulk updates within seeder files. This is particularly useful when you need to adjust your seeded data without manually updating each record.

await queryInterface.bulkUpdate('Birds', 
  { latitude: 70.0000, longitude: 130.333333 },
  { species: "Great Blue Heron" }
);
  

If you need to ensure that validations run during the update, you can include options such as { validate: true, individualHooks: true }.

Practical Follow-Along Exercise

Let’s walk through an example:

Imagine you have a Bird model representing birds observed in the field. You notice that the longitude for "Great Blue Heron" is wrong. Follow these steps:

Step 1: Find the bird record.

const greatBlueHeron = await Bird.findOne({ where: { species: "Great Blue Heron" } });
  

Step 2: Update the longitude by reassigning the value.

greatBlueHeron.longitude = 81.623863;
  

Step 3: Save the changes to the database.

await greatBlueHeron.save();
  

Now, try updating both the latitude and longitude using the set method:

greatBlueHeron.set({
  latitude: 58.936047,
  longitude: 81.623863
});
await greatBlueHeron.save();
  

Finally, practice updating multiple records using the Model.update method:

await Bird.update(
  { latitude: 70.0000, longitude: 130.333333 },
  { where: { id: { [Op.or]: [1, 2] } } }
);
  

Run these examples in your development environment and observe how the changes reflect in your database.

Real-World Applications

In a real-world scenario, imagine a weather application that tracks bird migration. If you receive updated GPS coordinates for certain bird species, you can efficiently update the records with minimal downtime. Similarly, e-commerce applications often need to update product details like pricing or stock levels in bulk when sales occur or inventory is refreshed.

These update methods provide you with flexible options depending on whether you need to update a single record or multiple records at once, ensuring data remains current and accurate.

Additional Topics to Explore

Once you are comfortable with basic update operations, consider exploring:

Conclusion

In this tutorial, you learned multiple ways to update data in Sequelize:

Each method has its own use case and benefits. By understanding and applying these methods, you can ensure that your data remains consistent, current, and reflective of real-world changes. Whether you're updating a single bird's coordinates or refreshing the inventory for an online store, Sequelize provides the flexibility and control you need.

Happy coding, and may your updates always hit the mark!