Using Sequelize with typescript and express : Import all model files

February 17, 2019

STEP 1    Install Sequelize

Install the latest version of Sequelize

Now create your migration script

STEP 2  Initialize your project

To create an empty project you  need to run init command

This will create seeders, config, migrations and models folders

Modify the configuration file in your config folder accordingly

 

Step 3 Create your model and migration files

This will create Migration files in the migrations folder and model files in the models folder

Step 4 Using models with typescript and express

When you create multiple tables multiple model files will be created. To use all these model files at once, create a model folder in your project directory, create an index.ts file and include all the files using the fs module and path module of Node.js

 

The index.ts file will look like this

 

The code

finds the model folder which is  outside your server files folder

__dirname – Gives the current directory in which the executing file is located

Finds all .js model files inside the models folder

sequelizeconnection.import  import model files.In this case, it imports all model files

Above code adds the model to the model object

The code above associate model files.

Step 5 Using models in the controller

 

 

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *