我在普通的 nodejs 基础上经常使用 mongoose,并且我也开始使用 NestJS。 Mongoose 定义了两件事,以便您可以使用 mongodb 创建、查询、更新和删除文档:Schema 和 Model。你已经有了你的模式,对于普通猫鼬的模型应该是:
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);
这里的收藏将是猫鼬模型。到目前为止一切顺利。
在 NestJs 中,如果您要遵循 API 最佳实践,您将使用 DTO(数据传输对象)。文档中的 NestJs 提到使用类比使用接口更可取,因此您在这里不需要接口。定义 Mongoose 架构时,也可以定义 Model/Schema:
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);
对于您的服务和控制器,您同时使用(模型和 DTO):
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(CollectionDto);
return createdCollection.save();
}
async findAll(): Promise<Collection[]> {
return this.collectionModel.find().exec();
}
}
在此之后,您可以使用 Swagger 自动生成 API 文档。
NestJS Mongo Techniques