MongoDB

Install mongoose

    npm i @nestjs/mongoose mongoose

Add Module

  • app.module.ts
    import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
})
export class AppModule {}

Create Schema

  • schemas/cat.schema.ts

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

export type CatDocument = HydratedDocument<Cat>;

@Schema()
export class Cat {

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

@Prop()
age: number;

@Prop()
breed: string;

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


}

export const CatSchema = SchemaFactory.createForClass(Cat);

Reference Collection

    @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' })
owner: Owner;

@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' }] })
owner: Owner[];

Record

    @Prop(
raw({
firstName: { type: String },
lastName: { type: String }
})
)
details: Record<string, any>;

Without Decorators

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

Include Schema in module

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

Service

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