ORM : Sequelize
Ruxin Qu
Posted on November 16, 2022
- Sequelize only provides ORM, to interact with a database, a database driver is still needed, like mysql2.
- In sequelize, database tables are referred as models. A model is an abstraction that represents a table in the database.
- To create a database connection, put the database name, username and password in an environment variable.
require('dotenv').config()
const {Sequelize} = require('sequelize')
sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USERNAME,
process.env.DB_PASSWORD,
{
host: process.env.DB_HOST,
dialect: 'mysql'
}
);
4 To create an instance of Model, use sequelize.define()
or class User extends Model
. The instance can have method.
const { Model, DataTypes } = require('sequelize');
class User extends Model {
async checkPassword(password) {
try {
const matchPassword = await bcrypt.compare(password, this.password);
return matchPassword;
} catch (err) { console.error(err); }
}
}
5 By default, sequelize add createAt and updateAt columns, to prevent it use timestamps: false
. freezeTableName: true
will make the table name same with model name.
6 sequelize.sync({force: true})
will synchronize the model to database. It creates a new table and drops the existing one first.
7 Sequelize hooks are functions called before or after sequelize calls are executed. The code below will hash the password everytime before a new user is created and saved.
hooks: {
beforeCreate: async (userData) => {
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(userData.password, salt);
userData.password = hashedPassword;
},
},
8 Populate the database: model.create()
or model.bulkCreate()
. model.update()
to update the data. model.destroy()
to delete the data.
9 Three common types between tables: one to one, one to many and many to many.
- One to One
User.hasOne(Passport)
Passport.belongsTo(User)
- One to many
User.hasMany(Post)
Post.belongsTo(User)
- Many to many: The studentClass table will have three columns: id, student_id and class_id
Student.belongsToMany(Class, {through: studentClass, foreighKey: student_id})
Class.belongsToMany(Student, {through: studentClass, foreignKey: class_id})
10 model.findAll()
can find all the data in the mobel. It can be used with where clause and operators
const postData = await Post.findAll(
{
where: { user_id: req.user.id },
include: { model: User }
});
11 model.findOne()
will return the one matching data. It can include the data from other models.
const postData = await Post.findOne({
where: { id: req.params.id },
include: [
{ model: User },
{
model: Comment,
include: [User] // here is a join of comment and user table
}]
});
Posted on November 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.