Sequelize Database Connection with Nodejs

Koray Göçmen
3 min readNov 21, 2020


Nodejs + Sequelize

After using Sequelize in my Express applications for the past 6 years, I’ve landed on a database file that I’ve been using for all my Nodejs applications.

Install sequelize with npm first and initialize the project with “sequelize init”. That should create the “models”, “migrations” and “seeders” folders as well as create the “config/config.json” file.

In our application, we’ll have users and cards. Each user can have multiple cards.

We need a users table and a cards table in our database and users will have a one-to-many relationship to cards. You can find how those migrations and the models are written here:

After creating the migrations and the models, we need to create the “association” for Sequelize to do its magic.

I define the associations inside my “lib/database.js” file, database file also has the database connection function.

// lib/database.js"use strict";

const Sequelize = require("sequelize");

const Config = require("../config/config")[process.env.NODE_ENV];

let sequelize = null;

exports.Connect = () => {
if (sequelize === null) {
sequelize = new Sequelize(Config.database, Config.username, Config.password, {
logging: process.env.NODE_ENV === "production" ? false : console.log,

console.log("Environment: " + process.env.NODE_ENV);
.then(() => {
console.log("Connection to database successfull");
.catch(err => {
console.log("Unable to connect to the database", err);

const DB = {
USER: sequelize.import("../models/User"),
CARD: sequelize.import("../models/Card"),

SEQUELIZE: Sequelize,

// User and Card association
DB.USER.hasMany(DB.CARD, {
foreignKey: "user_id",
sourceKey: "id",
DB.CARD.belongsTo(DB.USER, {
foreignKey: "user_id",
sourceKey: "id",

return DB;

Keeping the sequelize connection as a global variable allows me to reuse the connection.

DB variable holds the models that will be used when the database is needed.

Here is how the database connection is used in the controllers.

// controllers/users.js"use strict";

const Bcrypt = require("bcryptjs");
const Jwt = require("jsonwebtoken");

const Env = require("../../lib/env");
const Errors = require("../../lib/errors");
const Database = require("../../lib/database");
const Generator = require("../../lib/generator");
const Definitions = require("../../lib/definitions");

const DB = Database.Connect();

// Create a new user on the database with a new auth token.
exports.Create = async (req, res, next) => {
const {
} = req.body;

try {
const foundUser = await DB.USER.findOne({
where: {
email: email,

if(foundUser) {
return res.status(200).json({
success: false,
error: "Email already exists",

const authToken = Jwt.sign({ email: email }, Env.KEY.JWT);
const emailVerificationToken = await Generator.GenerateToken(20);
const passwordHash = Bcrypt.hashSync(password, Bcrypt.genSaltSync(10));

const user = await DB.USER.create({
email: email,
password: passwordHash,
authToken: authToken,
emailVerificationToken: emailVerificationToken,

success: true,
user: user.purge(),

} catch(err) {
success: false,
error: "Something went wrong",

You can find how to write the users and cards migrations and models here:

That’s pretty much it. The above code is actually from Violetnorth’s API. If you need to secure your website and your corporate email, you can check out Violetnorth.

Smart web and email firewall to secure your entire infrastructure:

Thanks for stopping by!



Koray Göçmen

University of Toronto, Computer Engineering, architected and implemented reliable infrastructures and worked as the lead developer for multiple startups.