The Startup
Published in

The Startup

Sequelize Database Connection with Nodejs

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!




Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

Recursive — Recursive Find Shortest String

What is it Axios & Why you need it?

5 Things That Eliminate Most of a Programmer’s Biggest Problems

React Hooks, The basics

Understanding the Fetch API in JavaScript

The fetch API in JavaScript.

Streams and Buffers in Node.js

Phases of the Node JS Event Loop

How A Single JavaScript Library Can Break The Internet In Two Lines Of Code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Koray Göçmen

Koray Göçmen

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

More from Medium

My Basic Guide for setting up AWS SAM (nodejs + Lambda + API Gateway) Part 1

How to Build REST API with Node.js, Express, and PostgreSQL

Node.js| An Explanatory Review