Mongoose Module

MongoDB with the Mongoose Module

No MongoDB 1,815 server runs on this machine, so unlike every other listing in this section the code below was not executed here. MongoDB installs MongoDB and runs these models against it. What follows is the wiring, so you can see which files change when the memory store of Providers and DI is replaced. @nestjs/mongoose 12.0.0 wraps Mongoose 243,355 as a module: the connection is configured from the validated config of the previous subsection, schemas are classes with decorators, and models are injected like any provider.

Connection, schema, model — and the store that replaces the memory oneJavaScript
MongooseModule.forRootAsync({ inject: [ConfigService],       // in app.module.ts
  useFactory: (c: ConfigService) => ({ uri: c.getOrThrow<string>('MONGO_URL') }) }),
@Schema({ timestamps: true, versionKey: false })             // books/book.schema.ts
export class Book {
  @Prop({ required: true, trim: true, maxlength: 200 }) title!: string;
  @Prop({ required: true, index: true }) authorId!: string; }
export const BookSchema = SchemaFactory.createForClass(Book);
// books.module.ts: MongooseModule.forFeature([{ name: Book.name, schema: BookSchema }])
@Injectable()                                                // data/mongo.store.ts
export class MongoStore {
  constructor(@InjectModel(Book.name) private readonly books: Model<Book>) {}
  async listBooks({ limit, offset, genre }: ListQuery) {
    const where = genre ? { genre } : {};
    return { total: await this.books.countDocuments(where),
      items: await this.books.find(where).skip(offset).limit(limit).lean().exec() };
  } }

Swapping it in is one provider registration — { provide: Store, useClass: MongoStore } in DataModule. Because every service depends on the Store token and not on a concrete class, the container rewires the whole application from that line, and no controller, DTO, guard or test changes. And .lean() is not optional there: without it Mongoose returns hydrated documents with save() and change tracking attached, and any service that uses them is welded to Mongoose.