How to Use Sequelize with NestJS: Setup and Example
To use
Sequelize with NestJS, install @nestjs/sequelize and sequelize packages, then import SequelizeModule in your module with database config. Define models as classes with decorators and inject them via @InjectModel() in services to interact with the database.Syntax
Use SequelizeModule.forRoot() to configure the database connection in your root module. Import SequelizeModule.forFeature() in feature modules to register models. Define models as classes decorated with @Table() and @Column(). Inject models in services using @InjectModel() to perform database operations.
typescript
import { Module } from '@nestjs/common'; import { SequelizeModule } from '@nestjs/sequelize'; import { User } from './user.model'; @Module({ imports: [ SequelizeModule.forRoot({ dialect: 'sqlite', storage: ':memory:', models: [User], autoLoadModels: true, synchronize: true, }), SequelizeModule.forFeature([User]), ], }) export class AppModule {} import { Table, Column, Model } from 'sequelize-typescript'; @Table export class User extends Model { @Column name: string; @Column email: string; } import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; @Injectable() export class UserService { constructor(@InjectModel(User) private userModel: typeof User) {} createUser(name: string, email: string) { return this.userModel.create({ name, email }); } }
Example
This example shows a simple NestJS app using Sequelize with SQLite in-memory database. It defines a User model, creates a user, and fetches all users.
typescript
import { Module, Injectable, OnModuleInit } from '@nestjs/common'; import { SequelizeModule, InjectModel } from '@nestjs/sequelize'; import { Table, Column, Model } from 'sequelize-typescript'; @Table export class User extends Model { @Column name: string; @Column email: string; } @Injectable() export class UserService implements OnModuleInit { constructor(@InjectModel(User) private userModel: typeof User) {} async onModuleInit() { await this.createUser('Alice', 'alice@example.com'); const users = await this.getAllUsers(); console.log('Users:', users.map(u => u.toJSON())); } createUser(name: string, email: string) { return this.userModel.create({ name, email }); } getAllUsers() { return this.userModel.findAll(); } } @Module({ imports: [ SequelizeModule.forRoot({ dialect: 'sqlite', storage: ':memory:', models: [User], autoLoadModels: true, synchronize: true, }), SequelizeModule.forFeature([User]), ], providers: [UserService], }) export class AppModule {}
Output
Users: [ { id: 1, name: 'Alice', email: 'alice@example.com', updatedAt: '...', createdAt: '...' } ]
Common Pitfalls
- Forgetting to import
SequelizeModule.forFeature()in modules where models are used causes injection errors. - Not setting
autoLoadModelsandsynchronizeto true can prevent models from syncing to the database. - Using plain JavaScript classes without decorators will not register models properly.
- Injecting models without
@InjectModel()decorator leads to undefined model instances.
typescript
/* Wrong: Missing SequelizeModule.forFeature import */ @Module({ imports: [SequelizeModule.forRoot({ dialect: 'sqlite', storage: ':memory:', models: [User] })], providers: [UserService], }) export class AppModule {} /* Right: Include SequelizeModule.forFeature */ @Module({ imports: [ SequelizeModule.forRoot({ dialect: 'sqlite', storage: ':memory:', models: [User], autoLoadModels: true, synchronize: true }), SequelizeModule.forFeature([User]), ], providers: [UserService], }) export class AppModule {}
Quick Reference
Sequelize with NestJS Cheat Sheet:
SequelizeModule.forRoot(config): Setup DB connection and models.SequelizeModule.forFeature([Model]): Register models in feature modules.@Tableand@Column: Decorate model classes and properties.@InjectModel(Model): Inject model into services.model.create(),model.findAll(): Use model methods for DB operations.
Key Takeaways
Install and import @nestjs/sequelize and sequelize packages to integrate Sequelize with NestJS.
Use SequelizeModule.forRoot() for database config and SequelizeModule.forFeature() to register models.
Define models as classes with @Table and @Column decorators from sequelize-typescript.
Inject models in services using @InjectModel() to perform database operations.
Enable autoLoadModels and synchronize for automatic model syncing during development.