SequelizeJS for Dummies
21.04.2021
Daniel Mocan
Content
What are ORM's?
Why SequelizeJS?
Setup
Models
Queries
Migrations
Demo
Q&A
What are ORM's
Object-Relational Mapping is a technique that lets you query and manipulates data from a database using an object-oriented paradigm. ORM loves objects as much as developers, and is available for any programming language of your choosing.
What are ORM's
Prons
easy to switch the database
Cons
protection agains SQL injection
same programming language
more advance features
complex SQL
initial setup
SQL expert
Why SequelizeJS
Probably the most used JS ORM
Multiple databases: Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server
around 4 million downloads pe month
actively being developed
preaty easy to use
lots of feature / options / configurations
Setup
# Core Packeage
npm install --save sequelize
# Dependecies for the type of database you want to use
npm install --save pg pg-hstore # Postgres
npm install --save mysql2
npm install --save mariadb
npm install --save sqlite3
npm install --save tedious # Microsoft SQL Server
Setup
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'storage/data.sqlite',
logging: console.log,
});
(async () => {
try {
await sequelize.authenticate();
await sequelize.sync();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
})();
module.exports = sequelize;
Models
const { DataTypes, Model } = require('sequelize');
const sequelize = require('./sequelize');
class Post extends Model {}
Post.init({
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
title: {
type: DataTypes.STRING,
allowNull: false
},
}, {
sequelize, // We need to pass the connection instance
modelName: 'Post' // We need to choose the model name
});
module.exports = Post;
Models
// creating an instance of a model
const firstPost = await PostModel.build({
title: "What is Binery?",
content: "Binery is a invented romania word. If is a cominations for Bine (good) and Vineri (Friday). Resulting word Binery express the feeling its good its Friday"
});
await firstPost.save();
// another option to create an instance of a model
const post = await PostModel.create({
title: "Third Post",
content: "long content"
});
Queries
const { Op } = require('sequelize');
// Finding a single post
const post = await Post.findOne({ id });
// Finding more mosts and count them
const { count, rows } = await Post.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
});
Queries
// Sequelize setup file
const sequelize = require('./sequelize');
//Simple select using RawQuery
const getPostsSQL = 'SELECT * FROM Posts';
const [results, metadata] = await sequelize.query(getPostsSQL);
// Even simpler so you don't have to get use the results
const { QueryTypes } = require('sequelize');
const posts = await sequelize.query(
'SELECT * FROM Posts',
{ type: QueryTypes.SELECT }
);
Migrations
npm install --save-dev sequelize-cli
// init will create a few folders like config, migrations, models, etc.
npx sequelize-cli init
Migrations
// Our first migration file
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Posts-migrations', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING
},
content: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Posts-migrations');
}
};
Demo
Thank you