Gre*_*mas 5 mongoose typescript nestjs
使用 vanilla Mongoose 时,可以直接向 Mongoose schemas 添加方法。Mongoose 文档很好地解决了这个问题,并且可以找到几个示例。
但是当您在 Nest 应用程序的上下文中使用 Mongoose 时呢?我希望我的 Mongoose 模式更像“Nest”,所以我使用了 Mongoose ( @nestjs/mongoose)的 Nest 包装器。但是,@nestjs/mongoose似乎缺少的文档。我能找到的与任何文档最接近的内容是在 Nest 应用程序中使用 MongoDB 的指南,其中仅包括 Mongoose 最绝对的基本用例。
在我看来,Mongoose 在 Nest 世界中的使用方式与 vanilla Mongoose 使用的方式大不相同。也许这只是缺乏对 TypeScript 或 Nest 的熟悉,但我似乎无法真正了解这些差异,而且缺乏示例也无济于事。
我在 StackOverflow 上看到了一些关于如何实现这一点的答案,例如:
我怎么能做这样的事情?
架构
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type CatDocument = Cat & Document;
@Schema()
export class Cat {
@Prop()
name: string;
@Prop()
age: number;
@Prop()
breed: string;
}
export const CatSchema = SchemaFactory.createForClass(Cat);
// ** Add methods here? **
Run Code Online (Sandbox Code Playgroud)
服务
import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './schemas/cat.schema';
@Injectable()
export class CatsService {
constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}
async findAll(): Promise<Cat[]> {
// Call our custom method here:
return this.catModel.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我设法做到的:
export type UserDocument = User & Document;
@Schema()
export class User extends Document {
@Prop({ required: true, unique: true })
email!: string;
@Prop({ required: true })
passwordHash!: string;
toGraphql!: () => UserType;
}
export const UserSchema = SchemaFactory.createForClass(User);
UserSchema.methods.toGraphql = function (this: User) {
const user = new UserType();
user.id = this._id;
user.email = this.email;
return user;
};
Run Code Online (Sandbox Code Playgroud)
刚刚添加
toGraphql!: () => 用户类型;
去上课
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |