Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.
Sequelize is an ORM (Object Relation Mapper) tool for Node JS. Sequelize uses the javascript object to store data in relational databases(i.e. MySQL, PostgreSQL, SQLite, and MariaDB, etc).
Sequelize takes data in object format, maps these objects with rows and columns, and also returns promises. We can use Sequelize to manage queries for any relational databases.
tutorials table.INSERT INTO `tutorials_db`.`tutorials`
(`id`,
`title`,
`author`,
`publishedAt`,)
VALUES
(5,
"Sequelize",
"AP Singh",
"2023-02-22",)const Tutorial = sequelizeInstance.define('tutorials', {
title: {
type: DataTypes.STRING,
allowNull: false,
},
author: {
type: DataTypes.STRING,
},
publishedAt: {
type: DataTypes.DATEONLY,
},
})
Tutorial.create({
title: 'Sequelize',
author: 'AP Singh',
publishedAt: '2023-02-27',
})create() method to insert data.In this section, We will create a node project and install sequelize. Then, We will create a database in MySQL and connect the Node JS application to MySQL using Sequelize.
sequelize-and-node-js as shown belowmkdir sequelize-and-node-jssequelize-and-node-js and initiate a node js projectcd sequelize-and-node-js
npm init -ysequelize-and-node-js in Visual Studio Code using the following command:code .package.json inside the folder sequelize-and-node-js.{
"name": "sequelize-and-node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}package.json file, Find and update a property named main as shown below"main": "server.js"server.js inside the folder sequelize-and-node-jssequelize-and-node-js
├─ package.json
├─ server.jssequelize using the following commandnpm install sequelize --saveMySQL database using the following command:$ mysql -u USER_NAME -pUSER_NAME with your MySQL database username, hit Enter and enter your MySQL database passwordtutorials_db in MySQL using the following command:mysql> CREATE DATABASE tutorials_db;tutorials_db is created successfully.mysql> SHOW DATABASES;+--------------------+
| Database |
+--------------------+
| mysql |
| performance_schema |
| tutorials_db |
| world |
+--------------------+npm install -save mysql2config.js inside the folder sequelize-and-node-js and add the following code// fileName: config.js
const MYSQL_DATABASE_USERNAME = 'Enter_Your_Database_Username'
const MYSQL_DATABASE_PASSWORD = 'Enter_Your_Database_Password'
module.exports = {
MYSQL_DATABASE_USERNAME,
MYSQL_DATABASE_PASSWORD,
}server.js file// fileName: server.js
const { Sequelize } = require('sequelize')
const { MYSQL_DATABASE_USERNAME, MYSQL_DATABASE_PASSWORD } = require('./config')
const sequelizeInstance = new Sequelize(
'tutorials_db', // databse name
MYSQL_DATABASE_USERNAME,
MYSQL_DATABASE_PASSWORD,
{
host: 'localhost',
dialect: 'mysql',
},
)sequelize ORM with new operator. Sequelize can accept various parameters and essential data credentials ( i.e. Database Name, Database Username, Database Password, etc)server.js file....
// Establish database connection
sequelizeInstance.authenticate()
.then(() => {
console.log("Connection to MySQL has been done successfully.")
})
.catch((error) => {
console.log("Not Connected! Try again", error)
});authenticate() method to establish a connection to the database and verify Whether the credentials are accurate.server.js file with the following command:
node server.jsConnection to MySQL has been done successfully.server.js file....
// Create model
const Tutorial = sequelizeInstance.define("tutorials", {
title: {
type: DataTypes.STRING,
allowNull: false
},
author: {
type: DataTypes.STRING,
},
publishedAt: {
type: DataTypes.DATEONLY,
},
});We used define() method to create a model that will create a table tutorials in the database tutorials_db.
Now, We will add Tutorial model to the database using sync() method and add the following code to the server.js file.
...
sequelizeInstance.sync()
.then(() => {
console.log("Successfully created the table: tutorials ")
})
.catch((error) => {
console.log("Error in creating table: tutorials", error)
})node server.js and it will display the following output:Executing (default): SELECT 1+1 AS result
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'tutorials' AND TABLE_SCHEMA = 'tutorials_db'
Connection to MySQL has been done successfully
Executing (default): CREATE TABLE IF NOT EXISTS `tutorials` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `author` VARCHAR(255), `publishedAt` DATE, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `tutorials`
Successfully created the table: tutorialstutorials is created.mysql> USE tutorials_db;
mysql> SHOW TABLES;+------------------------+
| Tables_in_tutorials_db |
+------------------------+
| tutorials |
+------------------------+
1 row in set (0.00 sec)tutorials is created successfully.Use create() method to add a new entry to the database and add the following code to the file addingNewRow.js
const { Sequelize, DataTypes } = require('sequelize')
const { MYSQL_DATABASE_USERNAME, MYSQL_DATABASE_PASSWORD } = require('./config')
const sequelizeInstance = new Sequelize(
'tutorials_db',
MYSQL_DATABASE_USERNAME,
MYSQL_DATABASE_PASSWORD,
{
host: 'localhost',
dialect: 'mysql',
},
)
const Tutorial = sequelizeInstance.define('tutorials', {
title: {
type: DataTypes.STRING,
allowNull: false,
},
author: {
type: DataTypes.STRING,
},
publishedAt: {
type: DataTypes.DATEONLY,
},
})
sequelizeInstance
.sync()
.then(() => {
Tutorial.create({
title: 'Sequelize: A Complete Guide',
author: 'Arun',
publishedAt: '2023-02-27',
})
.then((res) => {
console.log(res.dataValues)
})
.catch((error) => {
console.log('Error! Try again', error)
})
console.log('Data added to the table successfully')
})
.catch((error) => {
console.log('Error in creating table:', error)
})node addingNewRow.js and it will display the following output:{
id: 1,
title: 'Sequelize: A Complete Guide',
author: 'Arun',
publishedAt: '2023-02-27',
updatedAt: 2023-02-27T13:28:57.182Z,
createdAt: 2023-02-27T13:28:57.182Z
}bulkCreate() method to add new entries to the database and add the following code to the file addingRowsInBulk.jsconst { Sequelize, DataTypes } = require('sequelize')
const { MYSQL_DATABASE_USERNAME, MYSQL_DATABASE_PASSWORD } = require('./config')
const sequelizeInstance = new Sequelize(
'tutorials_db',
MYSQL_DATABASE_USERNAME,
MYSQL_DATABASE_PASSWORD,
{
host: 'localhost',
dialect: 'mysql',
},
)
const Tutorial = sequelizeInstance.define('tutorials', {
title: {
type: DataTypes.STRING,
allowNull: false,
},
author: {
type: DataTypes.STRING,
},
publishedAt: {
type: DataTypes.DATEONLY,
},
})
sequelizeInstance
.sync()
.then(() => {
Tutorial.bulkCreate([
{
title: 'Node JS: A Complete Guides',
author: 'Pratap',
publishedAt: '2023-02-24',
},
{
title: 'MySQL: A Complete Guides',
author: 'Singh',
publishedAt: '2023-02-20',
},
])
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log('Error! Try again', error)
})
console.log('Data added to the table successfully')
})
.catch((error) => {
console.log('Error in creating table:', error)
})node addingRowsInBulk.js and it will display the following output:[
tutorials {
dataValues: {
id: 2,
title: 'Node JS: A Complete Guides',
author: 'Pratap',
publishedAt: '2023-02-24',
createdAt: 2023-02-27T13:36:04.581Z,
updatedAt: 2023-02-27T13:36:04.581Z
},
_previousDataValues: {
title: 'Node JS: A Complete Guides',
author: 'Pratap',
publishedAt: '2023-02-24',
id: 2,
createdAt: 2023-02-27T13:36:04.581Z,
updatedAt: 2023-02-27T13:36:04.581Z
},
uniqno: 1,
_changed: Set(0) {},
_options: {
isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
include: undefined
},
isNewRecord: false
},
tutorials {
dataValues: {
id: 3,
title: 'MySQL: A Complete Guides',
author: 'Singh',
publishedAt: '2023-02-20',
createdAt: 2023-02-27T13:36:04.581Z,
updatedAt: 2023-02-27T13:36:04.581Z
},
_previousDataValues: {
title: 'MySQL: A Complete Guides',
author: 'Singh',
publishedAt: '2023-02-20',
id: 3,
createdAt: 2023-02-27T13:36:04.581Z,
updatedAt: 2023-02-27T13:36:04.581Z
},
uniqno: 1,
_changed: Set(0) {},
_options: {
isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
include: undefined
},
isNewRecord: false
}
]findAll() method to select entries in the database and add the following code to the file selectingAllRows.jsconst { Sequelize, DataTypes } = require('sequelize')
const { MYSQL_DATABASE_USERNAME, MYSQL_DATABASE_PASSWORD } = require('./config')
const sequelizeInstance = new Sequelize(
'tutorials_db',
MYSQL_DATABASE_USERNAME,
MYSQL_DATABASE_PASSWORD,
{
host: 'localhost',
dialect: 'mysql',
},
)
const Tutorial = sequelizeInstance.define('tutorials', {
title: {
type: DataTypes.STRING,
allowNull: false,
},
author: {
type: DataTypes.STRING,
},
publishedAt: {
type: DataTypes.DATEONLY,
},
})
sequelizeInstance
.sync()
.then(() => {
Tutorial.findAll({ raw: true })
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log('Failed to get the data', error)
})
})
.catch((error) => {
console.log('Error in syncing the table:', error)
})[
{
id: 1,
title: 'Sequelize: A Complete Guide',
author: 'Arun',
publishedAt: '2023-02-27',
createdAt: 2023-02-27T13:28:57.000Z,
updatedAt: 2023-02-27T13:28:57.000Z
},
{
id: 2,
title: 'Node JS: A Complete Guide',
author: 'Pratap',
publishedAt: '2023-02-24',
createdAt: 2023-02-27T13:36:04.000Z,
updatedAt: 2023-02-27T13:36:04.000Z
},
{
id: 3,
title: 'MySQL: A Complete Guide',
author: 'Singh',
publishedAt: '2023-02-20',
createdAt: 2023-02-27T13:36:04.000Z,
updatedAt: 2023-02-27T13:36:04.000Z
}
]where clausefindOne() method to select entries in the database and add the following code to the file usingWhereClause.jsconst { Sequelize, DataTypes } = require('sequelize')
const { MYSQL_DATABASE_USERNAME, MYSQL_DATABASE_PASSWORD } = require('./config')
const sequelizeInstance = new Sequelize(
'tutorials_db',
MYSQL_DATABASE_USERNAME,
MYSQL_DATABASE_PASSWORD,
{
host: 'localhost',
dialect: 'mysql',
},
)
const Tutorial = sequelizeInstance.define('tutorials', {
title: {
type: DataTypes.STRING,
allowNull: false,
},
author: {
type: DataTypes.STRING,
},
publishedAt: {
type: DataTypes.DATEONLY,
},
})
sequelizeInstance
.sync()
.then(() => {
Tutorial.findOne({
where: { id: '3' },
raw: true,
})
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log('Failed to get the data', error)
})
})
.catch((error) => {
console.log('Error in syncing the table:', error)
}){
id: 3,
title: 'MySQL: A Complete Guide',
author: 'Singh',
publishedAt: '2023-02-20',
createdAt: 2023-02-27T13:36:04.000Z,
updatedAt: 2023-02-27T13:36:04.000Z
}destroy() method to delete an entry from the database and add the following code to the file deletingRow.jsconst { Sequelize, DataTypes } = require('sequelize')
const { MYSQL_DATABASE_USERNAME, MYSQL_DATABASE_PASSWORD } = require('./config')
const sequelizeInstance = new Sequelize(
'tutorials_db',
MYSQL_DATABASE_USERNAME,
MYSQL_DATABASE_PASSWORD,
{
host: 'localhost',
dialect: 'mysql',
},
)
const Tutorial = sequelizeInstance.define('tutorials', {
title: {
type: DataTypes.STRING,
allowNull: false,
},
author: {
type: DataTypes.STRING,
},
publishedAt: {
type: DataTypes.DATEONLY,
},
})
sequelizeInstance
.sync()
.then(() => {
Tutorial.destroy({
where: { id: '3' },
})
.then(() => {
console.log('Successfully deleted data')
})
.catch((error) => {
console.log('Failed to delete data', error)
})
})
.catch((error) => {
console.log('Error in syncing the table:', error)
})Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE
TABLE' AND TABLE_NAME = 'tutorials' AND TABLE_SCHEMA = 'tutorials_db'
Executing (default): SHOW INDEX FROM `tutorials`
Executing (default): DELETE FROM `tutorials` WHERE `id` = '3'
Successfully deleted datanpm install sequelize.mysql2 driver to perform MySQL database queries. We can install mysql2 driver using the command npm install mysql2.authenticate() method to verify the database credentials and connect to the database.create() method.bulkCreate() method.findOne() method and where clause.findAll() method.destroy() method.