Mongo

Nest supports two methods for integrating with the MongoDB database. You can either use the built-in TypeORM module described here, which has a connector for MongoDB, or use Mongoose, the most popular MongoDB object modeling tool. In this chapter we’ll describe the latter, using the dedicated @nestjs/mongoose package.

Start by installing the required dependencies:

  1. $ npm install --save @nestjs/mongoose mongoose
  2. $ npm install --save-dev @types/mongoose

Once the installation process is complete, we can import the MongooseModule into the root AppModule.

app.module.ts

  1. import { Module } from '@nestjs/common';
  2. import { MongooseModule } from '@nestjs/mongoose';
  3. @Module({
  4. imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
  5. })
  6. export class AppModule {}

The forRoot() method accepts the same configuration object as mongoose.connect() from the Mongoose package, as described here.

Model injection

With Mongoose, everything is derived from a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. Schemas are used to define Models. Models are responsible for creating and reading documents from the underlying MongoDB database.

Schemas can be created with NestJS decorators, or with Mongoose itself manually. Using decorators to create schemas greatly reduces boilerplate and improves overall code readability.

Let’s define the CatSchema:

schemas/cat.schema.ts

  1. import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
  2. import { Document } from 'mongoose';
  3. @Schema()
  4. export class Cat extends Document {
  5. @Prop()
  6. name: string;
  7. @Prop()
  8. age: number;
  9. @Prop()
  10. breed: string;
  11. }
  12. export const CatSchema = SchemaFactory.createForClass(Cat);

Hint Note you can also generate a raw schema definition using the DefinitionsFactory class (from the nestjs/mongoose). This allows you to manually modify the schema definition generated based on the metadata you provided. This is useful for certain edge-cases where it may be hard to represent everything with decorators.

The @Schema() decorator marks a class as a schema definition. It maps our Cat class to a MongoDB collection of the same name, but with an additional “s” at the end - so the final mongo collection name will be cats. This decorator accepts a single optional argument which is a schema options object. Think of it as the object you would normally pass as a second argument of the mongoose.Schema class’ constructor (e.g., new mongoose.Schema(_, options))). To learn more about available schema options, see this chapter.

The @Prop() decorator defines a property in the document. For example, in the schema definition above, we defined three properties: name, age, and breed. The schema types for these properties are automatically inferred thanks to TypeScript metadata (and reflection) capabilities. However, in more complex scenarios in which types cannot be implicitly reflected (for example, arrays or nested object structures), types must be indicated explicitly, as follows:

  1. @Prop([String])
  2. tags: string[];

Alternatively, the @Prop() decorator accepts an options object argument (read more about the available options). With this, you can indicate whether a property is required or not, specify a default value, or mark it as immutable. For example:

  1. @Prop({ required: true })
  2. name: string;

Finally, the raw schema definition can also be passed to the decorator. This is useful when, for example, a property represents a nested object which is not defined as a class. For this, use the raw() function from the @nestjs/mongoose package, as follows:

  1. @Prop(raw({
  2. firstName: { type: String },
  3. lastName: { type: String }
  4. }))
  5. details: Record<string, any>;

Alternatively, if you prefer not using decorators, you can define a schema manually. For example:

  1. export const CatSchema = new mongoose.Schema({
  2. name: String,
  3. age: Number,
  4. breed: String,
  5. });

The cat.schema file resides in a folder in the cats directory, where we also define the CatsModule. While you can store schema files wherever you prefer, we recommend storing them them near their related domain objects, in the appropriate module directory.

Let’s look at the CatsModule:

cats.module.ts

  1. import { Module } from '@nestjs/common';
  2. import { MongooseModule } from '@nestjs/mongoose';
  3. import { CatsController } from './cats.controller';
  4. import { CatsService } from './cats.service';
  5. import { Cat, CatSchema } from './schemas/cat.schema';
  6. @Module({
  7. imports: [MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }])],
  8. controllers: [CatsController],
  9. providers: [CatsService],
  10. })
  11. export class CatsModule {}

The MongooseModule provides the forFeature() method to configure the module, including defining which models should be registered in the current scope. If you also want to use the models in another module, add MongooseModule to the exports section of CatsModule and import CatsModule in the other module.

Once you’ve registered the schema, you can inject a Cat model into the CatsService using the @InjectModel() decorator:

cats.service.ts

  1. import { Model } from 'mongoose';
  2. import { Injectable } from '@nestjs/common';
  3. import { InjectModel } from '@nestjs/mongoose';
  4. import { Cat } from './schemas/cat.schema';
  5. import { CreateCatDto } from './dto/create-cat.dto';
  6. @Injectable()
  7. export class CatsService {
  8. constructor(@InjectModel(Cat.name) private catModel: Model<Cat>) {}
  9. async create(createCatDto: CreateCatDto): Promise<Cat> {
  10. const createdCat = new this.catModel(createCatDto);
  11. return createdCat.save();
  12. }
  13. async findAll(): Promise<Cat[]> {
  14. return this.catModel.find().exec();
  15. }
  16. }
  1. import { Model } from 'mongoose';
  2. import { Injectable, Dependencies } from '@nestjs/common';
  3. import { getModelToken } from '@nestjs/mongoose';
  4. import { Cat } from './schemas/cat.schema';
  5. @Injectable()
  6. @Dependencies(getModelToken(Cat.name))
  7. export class CatsService {
  8. constructor(catModel) {
  9. this.catModel = catModel;
  10. }
  11. async create(createCatDto) {
  12. const createdCat = new this.catModel(createCatDto);
  13. return createdCat.save();
  14. }
  15. async findAll() {
  16. return this.catModel.find().exec();
  17. }
  18. }

Connection

At times you may need to access the native Mongoose Connection object. For example, you may want to make native API calls on the connection object. You can inject the Mongoose Connection by using the @InjectConnection() decorator as follows:

  1. import { Injectable } from '@nestjs/common';
  2. import { InjectConnection } from '@nestjs/mongoose';
  3. import { Connection } from 'mongoose';
  4. @Injectable()
  5. export class CatsService {
  6. constructor(@InjectConnection() private connection: Connection) {}
  7. }

Multiple databases

Some projects require multiple database connections. This can also be achieved with this module. To work with multiple connections, first create the connections. In this case, connection naming becomes mandatory.

app.module.ts

  1. import { Module } from '@nestjs/common';
  2. import { MongooseModule } from '@nestjs/mongoose';
  3. @Module({
  4. imports: [
  5. MongooseModule.forRoot('mongodb://localhost/test', {
  6. connectionName: 'cats',
  7. }),
  8. MongooseModule.forRoot('mongodb://localhost/users', {
  9. connectionName: 'users',
  10. }),
  11. ],
  12. })
  13. export class AppModule {}

Notice Please note that you shouldn’t have multiple connections without a name, or with the same name, otherwise they will get overridden.

With this setup, you have to tell the MongooseModule.forFeature() function which connection should be used.

  1. @Module({
  2. imports: [
  3. MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }], 'cats'),
  4. ],
  5. })
  6. export class AppModule {}

You can also inject the Connection for a given connection:

  1. import { Injectable } from '@nestjs/common';
  2. import { InjectConnection } from '@nestjs/mongoose';
  3. import { Connection } from 'mongoose';
  4. @Injectable()
  5. export class CatsService {
  6. constructor(@InjectConnection('cats') private connection: Connection) {}
  7. }

Hooks (middleware)

Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins (source). Calling pre() or post() after compiling a model does not work in Mongoose. To register a hook before model registration, use the forFeatureAsync() method of the MongooseModule along with a factory provider (i.e., useFactory). With this technique, you can access a schema object, then use the pre() or post() method to register a hook on that schema. See example below:

  1. @Module({
  2. imports: [
  3. MongooseModule.forFeatureAsync([
  4. {
  5. name: Cat.name,
  6. useFactory: () => {
  7. const schema = CatsSchema;
  8. schema.pre('save', () => console.log('Hello from pre save'));
  9. return schema;
  10. },
  11. },
  12. ]),
  13. ],
  14. })
  15. export class AppModule {}

Like other factory providers, our factory function can be async and can inject dependencies through inject.

  1. @Module({
  2. imports: [
  3. MongooseModule.forFeatureAsync([
  4. {
  5. name: Cat.name,
  6. imports: [ConfigModule],
  7. useFactory: (configService: ConfigService) => {
  8. const schema = CatsSchema;
  9. schema.pre('save', () =>
  10. console.log(
  11. `${configService.get<string>('APP_NAME')}: Hello from pre save`,
  12. ),
  13. );
  14. return schema;
  15. },
  16. inject: [ConfigService],
  17. },
  18. ]),
  19. ],
  20. })
  21. export class AppModule {}

Plugins

To register a plugin for a given schema, use the forFeatureAsync() method.

  1. @Module({
  2. imports: [
  3. MongooseModule.forFeatureAsync([
  4. {
  5. name: Cat.name,
  6. useFactory: () => {
  7. const schema = CatsSchema;
  8. schema.plugin(require('mongoose-autopopulate'));
  9. return schema;
  10. },
  11. },
  12. ]),
  13. ],
  14. })
  15. export class AppModule {}

To register a plugin for all schemas at once, call the .plugin() method of the Connection object. You should access the connection before models are created; to do this, use the connectionFactory:

app.module.ts

  1. import { Module } from '@nestjs/common';
  2. import { MongooseModule } from '@nestjs/mongoose';
  3. @Module({
  4. imports: [
  5. MongooseModule.forRoot('mongodb://localhost/test', {
  6. connectionFactory: (connection) => {
  7. connection.plugin(require('mongoose-autopopulate'));
  8. return connection;
  9. }
  10. }),
  11. ],
  12. })
  13. export class AppModule {}

Testing

When unit testing an application, we usually want to avoid any database connection, making our test suites simpler to set up and faster to execute. But our classes might depend on models that are pulled from the connection instance. How do we resolve these classes? The solution is to create mock models.

To make this easier, the @nestjs/mongoose package exposes a getModelToken() function that returns a prepared injection token based on a token name. Using this token, you can easily provide a mock implementation using any of the standard custom provider techniques, including useClass, useValue, and useFactory. For example:

  1. @Module({
  2. providers: [
  3. CatsService,
  4. {
  5. provide: getModelToken(Cat.name),
  6. useValue: catModel,
  7. },
  8. ],
  9. })
  10. export class CatsModule {}

In this example, a hardcoded catModel (object instance) will be provided whenever any consumer injects a Model<Cat> using an @InjectModel() decorator.

Learn the right way!

  • Mongo - 图1 60+ chapters
  • Mongo - 图2 4+ hours of videos
  • Mongo - 图3 Official certificate
  • Mongo - 图4 Deep-dive sessions

Explore official courses

Async configuration

When you need to pass module options asynchronously instead of statically, use the forRootAsync() method. As with most dynamic modules, Nest provides several techniques to deal with async configuration.

One technique is to use a factory function:

  1. MongooseModule.forRootAsync({
  2. useFactory: () => ({
  3. uri: 'mongodb://localhost/nest',
  4. }),
  5. });

Like other factory providers, our factory function can be async and can inject dependencies through inject.

  1. MongooseModule.forRootAsync({
  2. imports: [ConfigModule],
  3. useFactory: async (configService: ConfigService) => ({
  4. uri: configService.get<string>('MONGODB_URI'),
  5. }),
  6. inject: [ConfigService],
  7. });

Alternatively, you can configure the MongooseModule using a class instead of a factory, as shown below:

  1. MongooseModule.forRootAsync({
  2. useClass: MongooseConfigService,
  3. });

The construction above instantiates MongooseConfigService inside MongooseModule, using it to create the required options object. Note that in this example, the MongooseConfigService has to implement the MongooseOptionsFactory interface, as shown below. The MongooseModule will call the createMongooseOptions() method on the instantiated object of the supplied class.

  1. @Injectable()
  2. class MongooseConfigService implements MongooseOptionsFactory {
  3. createMongooseOptions(): MongooseModuleOptions {
  4. return {
  5. uri: 'mongodb://localhost/nest',
  6. };
  7. }
  8. }

If you want to reuse an existing options provider instead of creating a private copy inside the MongooseModule, use the useExisting syntax.

  1. MongooseModule.forRootAsync({
  2. imports: [ConfigModule],
  3. useExisting: ConfigService,
  4. });

Example

A working example is available here.