简体   繁体   English

在 NESTjs 中使用猫鼬插件

[英]Use mongoose plugin in NESTjs

I am trying to use mongoose-paginate-v2, in the Nestjs project.我正在尝试在 Nestjs 项目中使用 mongoose-paginate-v2。 My schema is like this:我的架构是这样的:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type CarDocument = Car & Document;

import * as mongoosePaginate from 'mongoose-paginate-v2';

@Schema()
export class Car {
  @Prop({ required: true })
  id: number;

  @Prop({ required: true })
  brand: string;

  @Prop({ required: true })
  model: number;

  @Prop({ required: true })
  color: string;
}

export const CarSchema = SchemaFactory.createForClass(Car);

CarSchema.plugin(mongoosePaginate);

And my service like this:我的服务是这样的:

import { Injectable, HttpException } from '@nestjs/common';
import { Car, CarDocument } from './schemas/car.schema';
import { Model } from 'mongoose';

import { Cars } from './cars.mock';
import { InjectModel } from '@nestjs/mongoose';

export interface ICarInterface {
  id: number;
  brand: string;
  color: string;
  model: number;
}

@Injectable()
export class CarService {
  constructor(@InjectModel(Car.name) private carModel: Model<CarDocument>) {}
  private cars = Cars;
  public getCars(): Promise<any> {
    return this.carModel.paginate.
  }
}

here i am unable use this.carModel.paginate , getting error Property 'paginate' does not exist on type 'Model<CarDocument, {}, {}, {}>'在这里我无法使用this.carModel.paginate ,出现错误Property 'paginate' does not exist on type 'Model<CarDocument, {}, {}, {}>'

Please help.请帮忙。

The plugin adds methods to the model type, but since you're still using Model as the type, TypeScript doesn't know about it.该插件将方法添加到模型类型,但由于您仍然使用Model作为类型,TypeScript 不知道它。 In the types for mongoose-paginate-v2 , it opens up the mongoose module and adds a new interface PaginateModel .mongoose-paginate-v2 的类型中,它打开了mongoose模块并添加了一个新的接口PaginateModel For models where you've wired up the plugin, you'll use that instead of just Model .对于已连接插件的模型,您将使用它而不仅仅是Model

import { PaginateModel } from 'mongoose';

@Injectable()
export class CarService {
  constructor(@InjectModel(Car.name) private carModel: PaginateModel<CarDocument>) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM