Sequelize is an ORM (Object-Relational Mapping) tool for Node.js that supports multiple SQL databases and provides powerful model definitions and data manipulation methods. In real-world development, managing database schema changes is an important task, and Sequelize addresses this through two methods: Migrations and Syncing.
1. Using Syncing
Syncing is a straightforward method. By calling Sequelize's sync method, it automatically creates or updates database tables based on the model definitions.
javascriptconst { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('User', { username: DataTypes.STRING, birthday: DataTypes.DATE }); sequelize.sync({ force: true }) .then(() => { console.log('Database sync successful'); return User.create({ username: 'Alice', birthday: new Date(1984, 6, 20) }); }) .then(user => { console.log(user.toJSON()); });
In this example, the sync method is called with the force: true option, which specifies that if the table exists, it will be dropped and recreated. This is useful for development environments but potentially dangerous for production.
2. Using Migrations
Migrations are a more professional and controlled way to manage database changes. They record detailed changes between versions, with each change implemented through migration scripts.
Before using Sequelize migrations, you need to install the CLI tool:
bashnpm install --save sequelize-cli
Then, initialize the migration configuration:
bashnpx sequelize-cli init
This creates necessary folders and files, including a migrations folder for storing migration scripts.
Create a migration file:
bashnpx sequelize-cli migration:generate --name create-users
This will create a new migration script in the migrations folder. You need to edit this file to define the specific table structure changes:
javascript'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable('Users', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, username: { type: Sequelize.STRING }, birthday: { type: Sequelize.DATE } }); }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable('Users'); } };
Finally, run the migration to update the database:
bashnpx sequelize-cli db:migrate
Migrations provide high-level control and flexibility, allowing you to maintain consistency of database structure across multiple environments and easily roll back to a previous state.
Summary
Using the syncing method is suitable for rapid development or small projects, while migrations are better suited for production environments or scenarios requiring detailed tracking of database changes. In real-world development, it is important to choose the appropriate method for managing database structure based on project-specific requirements and team workflows.