How to integrate an existing MSSQL database using NestJS and Sequelize

It’s hard to find info on but the process is quite simple…

Lots of tutorials start off with brand new projects and databases but what about those of us who need to integrate with an existing one? In this article we show you how to integrate an existing Microsoft SQL database into NestJS using Sequelize.

Photo by Florian Olivo on Unsplash

# Step 1 — Install dependencies

We’ll be using sequelize-typescript for this example so first run these npm commands to get the required dependencies

# Step 2 — Set up Sequelize in NestJS

First create a folder called ‘database’ in the ‘src’ directory

Second create two files ‘database.module.ts’ and ‘database.provider.ts’

Third add to the database module with the following code

Fourth add to ‘app.module.ts’

Fifth add the following code to ‘database.provider.ts’

Make sure to update the fields in with your database configuration.

That gets us started, notice the ‘sequelize.addModels([])’. We’ll be adding our models/database tables here. We’ve also configured an option for ‘freezeTableName’. This prevents automatically pluralizing the table name when selecting from the database table. We’ve also removed ‘sequelize.sync()’ to prevent overwriting our tables.

# Step 3 — Map Model to table

We can now map our first model! In sequelize each model represents a database table. Lets say we have a database table named ‘Cat’.

We also need to access those columns so we’ll create a provider for our code

Add these to our module for the component

And now we’re ready to use it

# Step 4 — Implement

Now that we’ve setup the connection and access to our table we can now use Sequelize to get data from our database. Make sure to add our database provider and cat provider to our ‘cat.service.ts’ file.

and Voila! We can now use an existing database connection with NestJS and Sequelize. For different tables replicate Steps 3 and 4 and change the entity name to match the table name. Don’t forget to add your exported entities to the ‘database.module.ts’ file.

Thanks for reading!



Philosophical Software Developer —

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