When working with databases you can choose to use the primitives offered by the database, or use a library that builds on top and abstract the tiny details for you.

Sequelize is one of those libraries, and it’s a very popular Node.js wrapper for PostgreSQL, MySQL and other databases.

In this post I’m going to explore how to use Sequelize to work with a PostgreSQL database.

Install and configure Sequelize

Under the hood, Sequelize uses the pg library to connect to PostgreSQL, so when we install the sequelize npm package, we also need to install pg:

npm install pg sequelize

Tip: don’t forget to first run npm init -y if the project is brand new and you don’t have a package.json file already.

In your Node.js file, you first define the database access variables:

const user = '<postgres user>'
const host = 'localhost'
const database = '<postgres db name>'
const password = '<postgres password>'
const port = '<postgres port>'

Then import 3 objects from sequelize:

import { Sequelize, Model, DataTypes } from 'sequelize'

Then you can initialize a new Sequelize object instance using this syntax:

const sequelize = new Sequelize(database, user, password, {
  host,
  port,
  dialect: 'postgres',
  logging: false
})

We tell Sequelize which kind of database this is in the dialect property (as mentioned, it can handle more than just Postgres).

We also disable logging, because it can be very verbose as it logs all the SQL queries, which we don’t really need to look at (unless you’re debugging a problem).

How to create a Sequelize model

For every table you want to manipulate using Sequelize, you create a model.

Here’s an example, suppose we have a dogs table with two columns: name and age.

We create a Dog class extending the Model base class:

import { Sequelize, Model, DataTypes } from 'sequelize'

const class Dog extends Model {}

Then call the init() static method on the class describing the data it contains and the rules we want to apply. In this case, we disable null:

Dog.init({
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  age: {
    type: DataTypes.INTEGER,
    allowNull: false
  }
}, {
  sequelize,
  modelName: 'dog',
  timestamps: false
})

We used DataTypes.STRING and DataTypes.INTEGER. The DataTypes object contains reference to all the types we can use, and they map to each specific database type. See the official docs for more types you can use.

How to get data from the database

Now that we have a model, how do we get data out of a table?

We can use the findAll() method:

Dog.findAll()

Calling this method will return a list of all the rows, and we’ll assign it to a variable:

const results = await Dog.findAll()

We use await because findAll() returns a promise

To limit the columns we retrieve, pass an object with the attributes array:

Dog.findAll({
  attributes: ['age']
})

Add a WHERE clause to the query using the where property. For example, get all dogs with age 8:

Dog.findAll({
  where: {
    age: 8,
  }
})

Or get all dogs with age higher than 5:

Dog.findAll({
  where: {
    age: {
      [Op.gte]: 5,
    }
  }
})

More properties allow you to do other operations like limit and order:

Dog.findAll({
  limit: 10,
  order: [
    ['name', 'DESC']
  ]
})

How to insert data into the database

We can call Dog.create() passing an object to create a new row in the database:

const name = 'Roger'
const age = 8
const result = await Dog.create({ name, age })

How to update data

Use the update() method to update values in the table.

In this example I set the age of ‘Roger’ to 9:

Post.update({
  age: 9
}, {
  where: {
    name: 'Roger'
  }
})

Removing the where property will update all rows:

Post.update({
  age: 10
})

Download my free Node.js Handbook, and check out my premium Node.js Course