Creating Models Using Sequelize

Posted on by By Gagan Manda, in Databases | 0

Sequelize is an ORM tool which is used to save data from node application to the databases like MySQL, Potgres and many other and a Model is basically a table in the database.

In this blog we will go through creating models in MySQL and for this we should have node and express application setup ready

In our application we should create a folder named models and folder config which contains the information to connect to database and the config file is as follows

{
"development":
{
"username": "root",
"password": "root",
"database": "database_name",
"host": "127.0.0.1",
"dialect": "mysql",
"timezone": "+05:30",
"logging": false
}
}

From the above code the host is the IP of the database and the username and password are the username and the passwords of the database and dialect defines to which database we are connecting and timezone we should specify our timezone as in the models created will have the columns CreatedAt and UpdatedAt hich will be having those corresponding times and the final Logging is when the server is running if a query Is executed that query will be displayed in the console if the logging is true and it will not be displayed if that is false.

In the server.js file where we setup the express we should add the var db = require(“./models”) and we should connect to our database using express and is as follows

db.sequelize.sync().then(function() {
app.listen(PORT, function() {
console.log("==> , PORT, PORT);
})
})
.catch(err => {
console.error('Unable to connect to the database ', err);
});

In the Models folder we should have and index.js file which is the entry point of the folder. In this folder we should create a separate file for each model that is to be created , in our case we can try creating a sample contacts page . For this we should create a Models/Contact.js file and the code is as follows

'use strict';
module.exports = (sequelize, DataTypes) => {
var contacts= sequelize.define('contacts', {
username: {
type : DataTypes.STRING,
allowNull : false,
unique : false
},
email: {
type : DataTypes.STRING,
allowNull : true,
unique : false
},
{
tableName: 'contacts'
}
});

return contacts;
};

In the above code we are defining a model with name contacts which contains the column names as username, email and for each column we should specify the type and in models/index.js file we will specify the configuration for the sequelize modal creation and the code is as follows

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
// this is the file which has the database connection details
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
//for all the individual js files present in /models it will check and create models

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

and when we start our server , it will execute the code db.sequelize.sync() present in server.js and then the command will be in /models as db containing models. In /models the entry point is index.js and in index.js we are using config.js in config folder where the database connection details are present and then after successful connection It will check for all the other files in /models folder and create respective models.

In the models created we will be having a few default columns such as id, CreatedAt, UpdatedAt where id is the primary key and auto-incremented value and createdAt and UpdatedAt tracks the stores the time and date of creating and updating the specific record. The model created with sample data will be as follows

In case if you have any queries please get back to us at support@helicaltech.com

Thank you,
Gagan Manda
BI Developer
Helical IT solutions

logo

Best Open Source Business Intelligence Software Helical Insight Here

logo

A Business Intelligence Framework


logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments