【问题标题】:Nestjs typesafe mongoose, model functions not asking for correct types (any)Nestjs typesafe mongoose,模型函数不要求正确的类型(任何)
【发布时间】:2020-04-25 04:26:51
【问题描述】:

Shema 接口

export interface MyCat {
  name: string;
  color: string;
}

export type Cat = MyCat & Document;

export const CatSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  color: {
    type: String,
    required: true,
  }
});

函数接收到的Dto(注意它没有颜色属性)

export class CreateCatDto {
  @IsString()
  readonly name: string = 'Franco';
}

函数调用,它在 new Cat(cat) 上没有错误,在运行时在 mongoose 上给出错误,说缺少必需的属性

  constructor(@InjectModel('Cat') private readonly catModel: Model<Cat>) {}

  async create(cat: CreateCatDto) {
    // typescript should give me an error here :(
    const createdCat = new this.catModel(cat);
    return await createdCat.save();
  }

我的问题是,如何让模型函数理解它们需要正确接收的内容?据我所见,他们经常接受any 类型

【问题讨论】:

    标签: typescript mongoose nestjs


    【解决方案1】:

    你可以使用 Typegoose https://typegoose.github.io/typegoose/ 用于类型安全建模

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 2021-08-15
      • 2020-04-24
      • 2021-06-25
      • 2020-02-26
      • 2018-10-22
      • 2021-10-22
      • 2020-10-02
      • 2020-08-16
      相关资源
      最近更新 更多