My experience with mongoose in plain nodejs has been extensive, and I am now delving into NestJS as well. Mongoose provides Schema and Model to interact with mongodb for document operations such as creation, querying, updating, and deletion. In plain mongoose, defining a model typically looks like this:
import * as mongoose from 'mongoose';
export const CollectionSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: false,
},
expiration: {
type: String,
required: true,
}
});
const Collection = mongoose.model('collections', CollectionSchema);
The 'Collection' here serves as the mongoose model. All good so far.
When working with NestJs and following API best practices, using a DTO (Data Transfer Object) is recommended. NestJs prefers classes over interfaces in this context. When defining a Mongoose schema, you can also define Model/Schema as shown below:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type CollectionDocument = Collection & Document;
@Schema()
export class Collection {
@Prop()
name: string;
@Prop()
description: number;
@Prop()
expiration: string;
}
export const CollectionSchema = SchemaFactory.createForClass(Collection);
For services and controllers in NestJs, both model and DTO are utilized:
import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Collection, CollectionDocument } from './schemas/collection.schema';
import { CollectionDto } from './dto/collection.dto';
@Injectable()
export class CollectionService {
constructor(@InjectModel(Collection.name) private collectionModel: Model<CollectionDocument>) {}
async create(createColDto: CollectionDto): Promise<Collection> {
const createdCollection = new this.collectionModel(createColDto);
return createdCollection.save();
}
async findAll(): Promise<Collection[]> {
return this.collectionModel.find().exec();
}
}
Utilize Swagger for automatic documentation of your APIs post implementation.
NestJS Mongo Techniques