[英]How can I add instance/static methods to Mongoose schema when using @nestjs/mongoose? (TypeScript Issues)
[英]How to define static mongoose methods in document interface while using @nestjs/mongoose?
Mongoose架構類 Mongoose集合用戶架構
const UserSchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
gender: {
type: String,
enum: Object.keys(GenderType),
required: true,
},
});
UserSchema.methods = {
fullName(): string {
return `${this.firstName} ${this.lastName}`;
},
};
UserSchema.statics = {
someAction(): string {
return '123';
},
};
export default UserSchema;
文件介面類別
貓鼬收集接口類
export interface IUser extends Document {
_id: Types.ObjectId;
firstName: string;
lastName: string;
gender: string;
fullName: () => string;
}
如何在使用@ nestjs / mongoose時在文檔界面中定義靜態貓鼬方法?
除了IUser
,您可能還需要一個額外的接口IUserModel
並將其從Model<T>
擴展。 示例代碼段可能如下所示:
export interface IUserModel extends Model<IUser> {
// Model is imported from mongoose
// you can put your statics methods here
someAction: () => string;
}
然后,在使用@InjectModel()
注入模型的任何地方,都可以鍵入IUserModel
類型的注入。
constructor(@InjectModel('UserModel') private readonly userModel: IUserModel) {}
現在,您的this.userModel
將可以訪問someAction()
方法。
編碼愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.