Adding a column in Sequelize typically involves two steps: first, updating the model definition, and then migrating the database to reflect these changes. Here are the detailed steps and examples:
Step 1: Update the Model Definition
Suppose we have a model named User, and we need to add a column named age to it. First, add this new column to the model definition:
javascriptconst { Model, DataTypes } = require('sequelize'); const sequelize = require('../path/to/your/sequelize_instance'); class User extends Model {} User.init({ // Existing columns username: DataTypes.STRING, email: DataTypes.STRING, // New column age: DataTypes.INTEGER }, { sequelize, modelName: 'User' }); module.exports = User;
In this example, we add a column named age with an integer data type.
Step 2: Database Migration
After updating the model, we need to add this column to the database. This can be achieved by manually modifying the database, using Sequelize's migration tool, or other database migration tools.
Using Sequelize Migration Tool
-
Generate the migration file: First, generate a migration file using Sequelize's command-line tool:
bashnpx sequelize-cli migration:generate --name add-age-to-usersThis creates a new migration file in the project's
migrationsdirectory. -
Write the migration logic: In the generated migration file, write the code to add the new column:
javascript'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.addColumn('Users', 'age', { type: Sequelize.INTEGER, allowNull: true }); }, down: async (queryInterface, Sequelize) => { await queryInterface.removeColumn('Users', 'age'); } };In this migration file, the
upmethod adds the column, while thedownmethod removes it for rollback purposes. -
Execute the migration: Run the following command to apply the migration:
bashnpx sequelize-cli db:migrate
By following these steps, we add the new column both at the model level and in the database, ensuring consistency between the code and the database.