【发布时间】:2020-12-18 20:55:10
【问题描述】:
所以我关注NestJS docs on MongoDB,但遇到了问题。
假设我得到了这个架构
// cat.model.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
@Schema()
export class Cat extends Document {
@Prop()
name: string;
@Prop()
info: string;
constructor(dto: CreateCatDTO) {
super();
this.name = dto.name;
// some algorithm to do stuff which I don't want to happen in the service
// since it's for the Cat model (SOLID)
this.info = dto.name + algorithmResultBlah;
}
}
export const CatSchema = SchemaFactory.createForClass(Cat);
但是.. 当我在服务中实例化它时
// cat.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Cat } from './interfaces/cat.model';
@Injectable()
export class CatsService {
constructor(@InjectModel("Cat") private readonly catRepository: Model<Cat>) {}
async create(dto: CreateCatDTO) {
const cat = new Cat(dto);
// I have to make a new instance to do some processing in the model..
// I don't want to do that in the service based on an interface because clutter
this.catRepository.create(cat);
}
}
上面的代码编译得很好,但是当我调用函数时,它给出了以下错误:
TypeError: Cannot read property 'plugin' of undefined
at Cat.Document.$__setSchema (~\node_modules\mongoose\lib\document.js:2883:10)
at new Document (~\node_modules\mongoose\lib\document.js:82:10)
at new Cat (~\dist\melding\domain\cat.js:7:9)
我怎样才能让它工作?一个星期以来,我一直在摸索(和谷歌)这个问题,我已经尝试了很多东西。
【问题讨论】:
-
有什么解决办法吗?