Sequelize with node and express
2 min readSep 6, 2019
Sequelize is orm(object relationa mapping) which helps us to map information between object and relational database such as mysql, MariaDb,SqlLite and PostgreSql, using sequelize we can communicate with database in form of model instead of raw query.
How to get started?
npm install --save sequelize
Setting up a project
mkdir sequelize_project, cd sequelize_project,
Here i am going to install connector for mysql because in this project i am using Mysql Database, you can install according to your database
$ npm install --save pg # for postgres
$ npm install --save mysql # for mysql
$ npm install --save sqlite3 # for sqlite
$ npm install --save mariasql # for mariasql
Connecting to the database
var Sequelize = require('sequelize')
, sequelize = new Sequelize('database_name', 'username', 'password', {
dialect: "mysql", // or 'sqlite', 'postgres', 'mariadb'
port: 3306, // or 5432 (for postgres)
});
sequelize
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
}, function (err) {
console.log('Unable to connect to the database:', err);
});module.exports = Sequelize;
file name - config.js
Defining a model
var student = sequelize.define('student', {
id: {type: sequelize.INTEGER(4), primaryKey: true}
Name: sequelize.STRING(50),
Address: {type:sequelize.STRING(500)}});module.exporst= student;file name- student.js
Reading data from the database
const express = require("express");
const app = express();
//database connection
require("./config.js")//import student model
let Model = require("./student.js")//Getting data from databaseapp.get("/", Model
.find({ where: { id: 50} })
.then(function(err, result) {
if (!result) {
console.log('No student with this id has been found.');
} else {
console.log('Hello 'user.Name'!');
}
})app.listen(3000, ()=>{console.log("running on port 3000")
})
for better understanding you can check this official link of sequelize https://sequelize.org/master/