Comprehensive Guide to Sequelize Mastering API Methods and Practical Usage

Introduction to Sequelize

Sequelize is a powerful Node.js ORM (Object-Relational Mapping) library, making it easy to communicate with databases. It supports multiple dialects like MySQL, PostgreSQL, SQLite, and MSSQL. This guide will introduce you to various Sequelize APIs with examples to help you harness its full potential.

Setup

 const { Sequelize, DataTypes, Model } = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', {
    host: 'localhost',
    dialect: 'mysql'
}); 

Model Basics

Define and synchronize a model:

 class User extends Model {} User.init({
    username: DataTypes.STRING,
    birthday: DataTypes.DATE
}, { sequelize, modelName: 'user' });
await sequelize.sync(); 

CRUD Operations

Create, Read, Update, and Delete examples:

Create a User:

 const jane = await User.create({
    username: 'janedoe',
    birthday: new Date(1980, 6, 20)
}); 

Read a User:

 const users = await User.findAll(); console.log(users.every(user => user instanceof User)); // true console.log("All users:", JSON.stringify(users, null, 2)); 

Update a User:

 const jane = await User.findOne({ where: { username: 'janedoe' } }); jane.username = 'janed'; await jane.save(); 

Delete a User:

 await User.destroy({
    where: {
        username: 'janed'
    }
}); 

Associations

Creating relationships between models:

 class Profile extends Model {} Profile.init({
    bio: DataTypes.TEXT
}, { sequelize, modelName: 'profile' });
User.hasOne(Profile); Profile.belongsTo(User);
await sequelize.sync(); 

Querying

Using different querying methods:

 const activeUsers = await User.findAll({
    where: {
        active: true
    }
});
const user = await User.findOne({
    where: {
        username: 'janedoe'
    }
}); 

Hooks

Using lifecycle events triggered by the ORM:

 User.beforeCreate((user, options) => {
    user.username = `user_${user.username}`;
});
const newUser = await User.create({
    username: 'john',
    birthday: new Date(1985, 5, 15)
}); console.log(newUser.username); // 'user_john' 

Instance vs Class Methods

Adding custom methods to models:

 User.prototype.greet = function() {
    return `Hello, ${this.username}!`;
};
console.log(jane.greet()); // 'Hello, janed!' 

A Complete App Example

Bringing it all together for a simple application:

 const express = require('express'); const app = express(); const port = 3000;
class User extends Model {} User.init({
    username: DataTypes.STRING,
    birthday: DataTypes.DATE
}, { sequelize, modelName: 'user' });
await sequelize.sync();
app.get('/users', async (req, res) => {
    const users = await User.findAll();
    res.json(users);
});
app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
}); 

Sequelize offers a rich set of features to easily manage your database operations in Node.js applications. Its intuitive API and versatile approach help you simplify complex database interactions with minimal effort.

Explore Sequelize further, and you will find it an invaluable tool in your Node.js toolkit.

Hash: d18291f313c7d19bbd05e9f351f9077f0825e78e7868d65c729c90d07b81903c

Leave a Reply

Your email address will not be published. Required fields are marked *