Why sequelize?
artemismars
Posted on March 15, 2022
I was using mongoose usually But some developers told me I need to learn SQL database too.
So, I decided to learn MySQL because someone introduced me 'planetscale' which is a MySQL Cloud Database service.
planetscale link
https://planetscale.com/
Anyway! We are going to use MySQL and sequelize in this post!
I explained why I use MySQL but What is sequelize now?
sequelize is a Node module that supports ORM(Object Relational Mapping). Shortly, I would say sequelize is an ORM tool.
Ok. But what is ORM?
You know Nodejs handles data from database via object data type.
for example,
const user = {
email: 'example@example.com',
password: '123123'
};
Since, NodeJS uses objects to deal with data from database in general. But SQL databases use tables and they are different from javascript objects.
But what if javascript objects are transformed to tables?
Then, Node Developers would handle the data with SQL databases easier.
That's what sequelize does!
I will write down some basic sequelize codes.
Then, you may think it is very similar with using mongoose!
db.js
const Sequelize = require('sequelize');
// You should install a database driver!
// for example, if you want to use mysql database then install mysql2 module.
// npm install mysql2
const sequelize = new Sequelize(database_name, username, password,
{
dialect: mysql,
host: '127.0.0.1'
});
// if you want to test the connection!
// you can use 'authenticate()' method.
(async () => {
try {
await sequelize.authenticate();
console.log('database connection successful');
} catch (error) {
console.log('database connection failed');
}
})();
module.exports = {Sequelize, sequelize}
The difference between Sequelize and sequelize is that Sequelize is a sequelize node module itself but sequelize is a connection to a database. Their names follow the convention recommended by the official sequelize document!
user.js
const {sequelize, Sequelize} = require('./db.js');
const User = sequelize.define('User', {
email: Sequelize.TEXT,
password: Sequelize.TEXT
},
{
timestamps: true
}
)
// User is now sequelize model!
console.log(sequelize.models.User === User); // true!
module.exports = User;
signup.js
const User = require('./user.js');
module.exports = async function(req, res) {
try {
const user = User.create({
email: req.body.email,
password: req.body.password
});
res.send(user);
} catch (error) {
res.send(error.message);
}
}
Next time! I will post the comparison between using mongoose, raw query and sequelize!
Thanks for reading my post! If you have some feedbacks, feel free to leave comments! thanks :)
Posted on March 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024