wuj*_*ryl 5 mongoose mongodb typescript nestjs
我是 NestJS 和 mongoDB 的新手,我不清楚为什么我们需要为要保存在 mongoDB 中的每个集合声明 DTO、模式和接口。IE。我有一个集合(不幸的是我已经命名了它,collection但这并不重要),这是我的 DTO:
export class CollectionDto {
readonly description: string;
readonly name: string;
readonly expiration: Date;
}
Run Code Online (Sandbox Code Playgroud)
界面:
import { Document } from 'mongoose';
export interface Collection extends Document {
readonly description: string;
readonly name: string;
readonly expiration: Date;
}
Run Code Online (Sandbox Code Playgroud)
和架构:
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,
}
});
Run Code Online (Sandbox Code Playgroud)
我的疑问是,我们真的需要多达三个内容几乎相同的对象吗?乍一看很奇怪。
我在普通的 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);
Run Code Online (Sandbox Code Playgroud)
这里收集的是猫鼬模型。到目前为止,一切都很好。
在 NestJs 中,如果您要遵循 API 最佳实践,您将使用 DTO(数据传输对象)。NestJs 在文档中提到使用类比接口更好,所以这里不需要接口。当你定义 Mongoose schema 时,你还可以定义 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);
Run Code Online (Sandbox Code Playgroud)
对于您的服务和控制器,您同时使用(模型和 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(createColDto);
return createdCollection.save();
}
async findAll(): Promise<Collection[]> {
return this.collectionModel.find().exec();
}
}
Run Code Online (Sandbox Code Playgroud)
之后,您可以使用 Swagger 来自动记录 API。 NestJS Mongo 技术