【问题标题】:Instantiating new Document in NestJS with mongoose crashes使用猫鼬崩溃在 NestJS 中实例化新文档
【发布时间】: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)

我怎样才能让它工作?一个星期以来,我一直在摸索(和谷歌)这个问题,我已经尝试了很多东西。

【问题讨论】:

  • 有什么解决办法吗?

标签: mongoose nestjs


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 2021-07-05
    • 2021-05-19
    • 2022-06-11
    • 2016-06-02
    • 2021-09-18
    • 2020-10-18
    • 2022-11-10
    • 2022-01-22
    相关资源
    最近更新 更多