Sequelize is a popular Object-Relational Mapping (ORM) library for Node.js, which supports multiple database systems, including MySQL. Using Sequelize with MySQL in a Node.js application involves several steps. Below is a basic guide to help you get started:
Install Dependencies: Start by installing Sequelize and the MySQL driver for Sequelize.
bashnpm install sequelize mysql2
The mysql2
package is the MySQL driver for Sequelize.
Set Up Sequelize:
Create a Sequelize instance and configure it to connect to your MySQL database. Create a file, e.g., db.js
:
javascriptconst { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
});
module.exports = sequelize;
Replace 'database'
, 'username'
, and 'password'
with your MySQL database information.
Define Models:
Create Sequelize models to represent your database tables. For example, create a User
model in a file like models/User.js
:
javascriptconst { DataTypes } = require('sequelize');
const sequelize = require('../db');
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
});
module.exports = User;
Adjust the model definition based on your database schema.
Sync Models with Database:
In your main application file, sync the defined models with the database. For example, in app.js
:
javascriptconst sequelize = require('./db');
const User = require('./models/User');
// Sync models with the database
(async () => {
try {
await sequelize.sync({ force: false }); // Set force to true to drop and re-create tables
console.log('Database synced successfully');
} catch (error) {
console.error('Error syncing database:', error);
}
})();
This code snippet synchronizes the models with the database. Note that using { force: true }
in sync
will drop and re-create tables, so be cautious in a production environment.
Perform Database Operations: Now you can use the defined models to perform CRUD operations. For example, to create a user:
javascriptconst User = require('./models/User');
(async () => {
try {
const newUser = await User.create({
username: 'john_doe',
email: 'john@example.com',
password: 'securepassword',
});
console.log('User created:', newUser.toJSON());
} catch (error) {
console.error('Error creating user:', error);
}
})();
Adjust the code according to your specific use case.
That's a basic guide to using Sequelize with MySQL in a Node.js application. Remember to handle database connection errors and use Sequelize's powerful features for querying and relationships as needed.