Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 42 ยท Data and Persistence

MongoDB with Mongoose

Use MongoDB in NestJS with @nestjs/mongoose: define schemas with decorators, register them with forFeature, inject models, write a CRUD service, populate references and compare with TypeORM.

The previous lessons in this chapter used relational databases. Connecting to a Database said that Nest is neutral about storage, and MongoDB is the most common non-relational choice. MongoDB stores documents, JSON-like objects grouped into collections, instead of rows in tables. Documents in one collection need not share a fixed shape, and related data is often embedded inside a document instead of joined.

In Nest, the usual way to work with MongoDB is Mongoose, an object-document mapper that adds schemas, validation and a friendly query API on top of the official driver. The @nestjs/mongoose package wires Mongoose into Nest's module and provider system. This lesson walks through the connection, a decorated schema, forFeature, a CRUD service, references with populate, and how the approach differs from TypeORM.

The framework and Mongoose code is read-only, because it needs a running MongoDB server. The runnable stand-ins are plain JavaScript: a miniature model class that validates documents and a service that receives the model by injection, so you can see why the pattern is easy to test.

Connecting

Install @nestjs/mongoose and mongoose, then register the connection once in the root module, ideally with the async form from Dynamic Modules and Provider Scopes so the URI comes from configuration:

TypeScript
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [
    MongooseModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        uri: config.getOrThrow<string>('MONGODB_URI'),
      }),
    }),
    CatsModule,
  ],
})
export class AppModule {}

A typical local URI is mongodb://127.0.0.1:27017/shop. Keep real credentials in environment variables, as for any database.

Defining a schema with decorators

A Mongoose schema describes the shape, types, defaults and validation rules of a document. With @nestjs/mongoose you write it as a class:

TypeScript
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';

export type CatDocument = HydratedDocument<Cat>;

@Schema({ timestamps: true })
export class Cat {
  @Prop({ required: true, trim: true, minlength: 2 })
  name: string;

  @Prop({ required: true, min: 0, max: 40 })
  age: number;

  @Prop({ enum: ['tabby', 'siamese', 'other'], default: 'other' })
  breed: string;

  @Prop([String])
  tags: string[];
}

export const CatSchema = SchemaFactory.createForClass(Cat);

@Schema() marks the class, @Prop() marks each field, and SchemaFactory.createForClass builds the actual Mongoose schema from the metadata. timestamps: true adds createdAt and updatedAt automatically. Mongoose also adds _id (an ObjectId) to every document. HydratedDocument<Cat> is the type of what Mongoose returns: your fields plus Mongoose's methods such as save().

Where @Prop() cannot infer a type (arrays, unions, nested objects) you pass it explicitly, as with @Prop([String]). Indexes are declared on the schema, for example CatSchema.index({ name: 1 }, { unique: true }), and unique indexes are the real guard against duplicates, just like database constraints in SQL.

Validation in a Mongoose schema runs when you call save() or create(), not on every query. It is a second line of defense. Validate incoming requests with DTOs and pipes first, so bad input never reaches the model.

Registering and injecting models

A feature module declares which schemas it uses, and Nest creates an injectable model for each:

TypeScript
@Module({
  imports: [MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }])],
  providers: [CatsService],
  controllers: [CatsController],
})
export class CatsModule {}

This is the same idea as TypeORM's forFeature: register once, inject where needed. The service injects the model with @InjectModel:

TypeScript
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class CatsService {
  constructor(@InjectModel(Cat.name) private readonly cats: Model<Cat>) {}

  create(dto: CreateCatDto) {
    return this.cats.create(dto);
  }

  findAll() {
    return this.cats.find().sort({ name: 1 }).lean().exec();
  }

  async findOne(id: string) {
    const cat = await this.cats.findById(id).exec();
    if (!cat) throw new NotFoundException(`Cat ${id} not found`);
    return cat;
  }

  async update(id: string, dto: UpdateCatDto) {
    const cat = await this.cats
      .findByIdAndUpdate(id, dto, { new: true, runValidators: true })
      .exec();
    if (!cat) throw new NotFoundException(`Cat ${id} not found`);
    return cat;
  }

  async remove(id: string) {
    const result = await this.cats.deleteOne({ _id: id }).exec();
    if (result.deletedCount === 0) throw new NotFoundException(`Cat ${id} not found`);
  }
}

A few details here prevent common mistakes:

  • .lean() returns plain objects instead of full Mongoose documents. It is faster and uses less memory for read-only responses, but you lose methods like save().
  • findByIdAndUpdate returns the old document unless you pass new: true, and it skips schema validation unless you pass runValidators: true.
  • A malformed id (not 24 hex characters) makes Mongoose throw a CastError. Check ids with a pipe, for example a ParseObjectIdPipe you write with Types.ObjectId.isValid, so clients get a clean 400 instead of a 500.
  • Always call .exec() (or await the query) so you get a real promise and proper stack traces.

References and populate

MongoDB has no joins in the SQL sense. You have two options for related data. Embed it when it is read together and owned by the parent (an address inside a user). Reference it when it is shared or large (a post pointing to its author). A reference stores the other document's _id:

TypeScript
import * as mongoose from 'mongoose';

@Schema({ timestamps: true })
export class Post {
  @Prop({ required: true })
  title: string;

  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true })
  author: User;
}
export const PostSchema = SchemaFactory.createForClass(Post);

populate('author') makes Mongoose run a second query and replace the id with the author document:

TypeScript
findPosts() {
  return this.posts.find().populate('author', 'name email').exec();
}

Populate is convenient, but it is not a database join: each populate is an additional round trip, and populating inside a long list can create the N+1 pattern you will see in the GraphQL track. Select only the fields you need, and think twice before populating deep chains. If you always read two things together, embedding is cheaper.

Mongoose or TypeORM?

Question Mongoose (MongoDB) TypeORM (SQL)
Data shape Flexible documents, embedded arrays Fixed tables, columns, relations
Schema lives in App code (and optional indexes) Database plus migrations
Relations Embed or ref + populate Joins, foreign keys
Transactions Supported on replica sets, used less Everyday tool
Good fit Content, catalogs, event logs, varied attributes Money, orders, strongly related data
Schema changes Old documents keep old shape until migrated Migration changes every row

Neither is "better". Choose by the shape and rules of your data. Flexible schemas do not remove the need to think about structure: you still need indexes, consistent field names and a plan for old documents when the shape changes. Money, inventory and anything that must stay consistent across several records usually fit a relational database better, as described in Transactions and Migrations.

Stand-in: a tiny model with schema validation

The stand-in below is not Mongoose. It is a small class that mimics the part you have just read: a schema with required, min, enum and default, and a model with create, findById, find and deleteOne. Ids are generated from a counter, where Mongoose would create an ObjectId.

Node.js A miniature schema and model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the unknown field admin: true was silently dropped. Mongoose does the same in its default strict mode, which is a useful defense against mass assignment, though you should still whitelist DTO fields in the request layer.

Stand-in: injecting the model, and testing with a fake

Because the service only receives a model through its constructor, a test can pass anything that has the same methods. This is exactly what getModelToken(Cat.name) and a custom provider let you do in a Nest testing module (see Testing Nest Applications). The stand-in shows both a populate-like lookup and a fake model.

Node.js A service that receives its model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two authors and three posts cost one posts query plus two user lookups. Real Mongoose batches a populate into a single $in query per path, but the cost model is the same: populate means extra queries, so plan for it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does SchemaFactory.createForClass(Cat) do?

    It reads the decorator metadata and returns the Mongoose schema object, which you pass to MongooseModule.forFeature.
  2. 2. How does a service obtain the Cat model?

    forFeature registers a provider under a token derived from the name, and @InjectModel injects it.
  3. 3. findByIdAndUpdate(id, dto) returns the old document. How do you get the updated one and run schema validators?

    By default the old document is returned and update validators are off. The two options change both.
  4. 4. What is true of populate('author')?

    MongoDB has no SQL-style join here. Populate performs additional queries, which is why embedding is sometimes better.
  5. 5. Which data is usually a better fit for a relational database than for MongoDB?

    Strong relations and multi-record consistency are the home turf of SQL transactions and foreign keys.

Summary

  • @nestjs/mongoose connects Mongoose to Nest: MongooseModule.forRootAsync for the connection, forFeature to register schemas.
  • Schemas are classes decorated with @Schema() and @Prop(), turned into Mongoose schemas by SchemaFactory.createForClass.
  • Inject a model with @InjectModel(Name) and write CRUD with create, find, findById, findByIdAndUpdate (new: true, runValidators: true) and deleteOne.
  • Use lean() for fast read-only results, and validate ids and input before they reach Mongoose.
  • Embed data that is read together; reference with ref and populate when documents are shared, remembering that populate costs extra queries.
  • Pick Mongoose or an SQL ORM by the shape and consistency needs of your data, not by fashion.

Next, call other services from your API in Calling External APIs with HttpModule.