用猫鼬崩溃实例化NestJS中的新文档

时间:2020-08-30 15:15:35

标签: mongoose nestjs

因此我正在关注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)

我该如何使用它?我已经为此花了一个星期挠头(和Google),并且尝试了很多事情。

1 个答案:

答案 0 :(得分:0)

您需要创建 Mongoose 模型的实例,而不是类实例。这应该有效

const cat = new this.catRepository(dto);
await cat.save();

const cat = await this.catRepository.create(dto);

我建议您将 catRepository 重命名为 CatModel,这样会更易于使用。 Nest 根据您的 TS 类中定义的模式创建模型,并在您需要的任何地方注入这些模型。也就是说,类只是一个类型糖,并不能真正作为类工作,它仅用于提供类型安全和生成模型的架构。