fbpx

How to use Sequelize with Node and Express

I will show you how to use sequelize with node and express in this post, you are going to learn how to define and load your model when working with a small or large application.

Before we can work with an express app their a few things to do which include creating a folder for our app and then install express using an npm or yarn command depend on your choice, but for the sake of this tutorial I will be using npm to setup our project and start creating our app.

Open your command line and type the following code line by line and execute.

$ mkdir example-app
$ cd example-app
$ npm install express express-generator
$ node_modules/.bin/express . -f
$ npm install
$ ./bin/www

Running the above code will generate a scaffold express app which is available on the URL – http://localhost:3000

NB: Don’t forget to run each code individually line by line.

The next step is to add a sequelize package to our project for simplicity we will need some packages to get us started as follows: sequelize, sequelize-cli, SQlite3.

$ npm install --save sequelize@2.0.0-rc1 sequelize-cli sqlite3

When the package finishes, next are to allow sequelize CLI initialize the project folder.

$ node_modules/.bin/sequelize init

When you run above command it will generate a folders namely config, migration, models.

Let start creating our app

How’s our app going to function? We will create a simple todo list application where users can manage their tasks.

In our “bin/www” folder is where we going to maintain app our app functions, all our database logic will reside in the model’s folder.  the application will build up when sequelize sync with the database then node server start on the above URL with port 3000.

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('express-sequelize');
var http = require('http');
var models = require('../models');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
  /**
   * Create HTTP server.
   */
var server = http.createServer(app);

models.sequelize.sync().then(function() {
  /**
   * Listen on provided port, on all network interfaces.
   */
  server.listen(port, function() {
    debug('Express server listening on port ' + server.address().port);
  });
  server.on('error', onError);
  server.on('listening', onListening);
});

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

Create an “index.js” file in your model’s folder, that will handle the loading of our model’s file without including them one by one when the server start.

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(__filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.js')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  var 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 => {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

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

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

module.exports = db;

Now that you have created a file to load your model’s file, let start creating our models for the todo-list app by creating a “user.js” model that will create a user’s table in our SQlite database.

'use strict';
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    username: DataTypes.STRING
  });

  User.associate = function(models) {
    models.User.hasMany(models.Task);
  };

  return User;
};

Read How to Start a Blog as a Programmer and Make Money

Since we are building a todo-list app that manages user tasks, then we will need a task model to associate a particular task to a user, for that let’s create a “task.js” file too.

'use strict';
module.exports = (sequelize, DataTypes) => {
  var Task = sequelize.define('Task', {
    title: DataTypes.STRING
  });

  Task.associate = function (models) {
    models.Task.belongsTo(models.User, {
      onDelete: "CASCADE",
      foreignKey: {
        allowNull: false
      }
    });
  };

  return Task;
};

Create an “index.js” file inside the routes folder that will handle all requests entering into the main homepage. It will automatically load the model’s folder and then proceed to initializes all models like user and task from there.

var models  = require('../models');
var express = require('express');
var router  = express.Router();

router.get('/', function(req, res) {
  models.User.findAll({
    include: [ models.Task ]
  }).then(function(users) {
    res.render('index', {
      title: 'Sequelize: Express Example',
      users: users
    });
  });
});

module.exports = router;

That will allow us to perform the user task in the view file.

Now that we have passed the users to our view and include the tasks for each user, we can navigate through the view file at “view/index.jade“. Besides listing the users and tasks, there are also forms for creating new instances.

What’s Next

We are able to cover integrating sequelize into the ExpreeJS application. This allows us to load all models from our model’s folder when the server starts without including them individually.

If you want to go in-depth with Node and Express building a robust application that you can include in your resume when applying for jobs.

Adewale Adetona

I'm a FullStack Developer and Digital Marketer. I started this blog to give you the proven strategies and resources you need to accelerate your career as a software developer.

Leave a Reply