How to use MongooseModule forFeature and forRoot on NestJS

Posted January 31, 2024
How to use MongooseModule forFeature and forRoot on NestJS

When working with MongoDB, you use Mongoose as the ORM. With Nest.js, Mongoose uses @nestjs/mongoose packages to access Typescript Mongoose support on the Nest.js app.

You will need MongooseModule from @nestjs/mongoose to integrate Mongoose with Nest.js. The MongooseModule comes with two methods: forRoot and forFeature. This means you will have MongooseModule.forRoot and MongooseModule.forFeature in your app. Each must be configured correctly. If not, Nest.js will fail to use Mongoose to access MongoDB.

This guide will teach you all you need to know about MongooseModule.forRoot and MongooseModule.forFeature. You will use a Nest.js app and learn how to correctly use MongooseModule to access Mongoose with forFeature and forRoot methods.

What is MongooseModule forRoot

The forRoot method will configure the Mongoose connection at the root level of NestJS. You add it as an imports array of your primary application module (AppModule).

What is MongooseModule forFeature

To use the forFeature method, you must have a Nest.js featured module. forFeature registers Mongoose models/schemas within feature modules. This way, you encapsulate the Mongoose-related configuration for that given feature module in a modular way.

Step One: How to implement MongooseModule forFeature and forRoot

Before using MongooseModule forFeature and forRoot, you must have a working Nets.js app configured with Mongoose. At the same time, you must have a Mongoose schema/model ready. First, create your app as follows:

# Make Nest.js CLI ready
npm i -g @nestjs/cli
# Create a simple Nest.js App
nest new nest-app

Now, you open your terminal pointing to the created nest-app app:

cd nest-app

To use MongooseModule forFeature and forRoot, Mongoose must be installed in your application:

npm install --save @nestjs/mongoose mongoose

Here, we have the MongooseModule forFeature method. This means you need to create a featured module using the following command (I will use users in this case):

nest g resource users --no-spec

How to use MongooseModule forFeature and forRoot on NestJS

This should create a users module. You should now go to the src\users\entities\user.entity.ts file and use Mongoose to create an entity. For example:

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";

@Schema()
export class User{
    @Prop()
    email:string;

    @Prop()
    password:string;

}

export const userSchema = SchemaFactory.createForClass(User)

Once you have the schema/model ready, let’s dive in and add MongooseModule forFeature and forRoot methods.

Step Two: Implementing MongooseModule forFeature Method

forFeature is used in feature modules to register Mongoose models and schemas specific to that feature. This means forFeature will be added to the UsersModule in the src\user\users.module.ts file.

Navigate to this file and import MongooseModule from @nestjs/mongoose, then implement forFeature as follows:

import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { MongooseModule } from '@nestjs/mongoose';
import { User, userSchema } from './entities/user.entity';

@Module({
  imports: [
    MongooseModule.forFeature([{ 
      name: 'User', 
      schema: 'userSchema' 
    }]),
  ],
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}

In this case,

  • MongooseModule.forFeature will register the Mongoose UsersModule feature module.
  • You will have an array of objects where each object has a name (model name) and schema (Mongoose schema).

In this User example, you will have:

  • name: 'User' to inject the model.
  • schema: userSchema to load the Mongoose schema with the structure of the User entity.

That’s all you need to let MongooseModule.forFeature register Mongoose models and schemas.

Step Three: How to use MongooseModule forRoot Method

Once you have MongooseModule.forFeature ready, you will need to use forRoot at the root on Nest.js. This will allow Mongoose to connect to your MongoDB database.

Here, changes will be added to AppModule in the src\app.module.ts file as follows:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { UsersModule } from './user/users.module';

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://127.0.0.1:27017/user_db', {
      
    }),
    UsersModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

MongooseModule.forRoot is good now.

Here:

  • The MongooseModule.forRoot method will initialize a Mongoose connection to your MongoDB database.
  • mongodb://127.0.0.1:27017/user_db is your MongoDB connection string, with the host, port, and database name.
  • MongooseModule.forRoot takes additional configuration options passed as objects as the second argument to forRoot.

Step Four: Create CRUD Mongoose Nest.js with this Setup

The next step is to use this configuration and create a CRUD nest.js app. I have created the following posts to help you use Mongoose and execute MongooseModule.forRoot and MongooseModule.forFeature while creating a full RESTful API:

Conclusion

I hope to have learned how to correctly add MongooseModule forFeature and forRoot methods to your NestJS apps.

How to use MongooseModule forFeature and forRoot on NestJS

Written By:

Joseph Chege