【问题标题】:What is the correct way to implement interfaces with node and mongoose?用节点和猫鼬实现接口的正确方法是什么?
【发布时间】:2021-10-15 11:35:51
【问题描述】:

我为我的模型创建了一个接口,我只想从记录中返回特定数据

// code.interface.ts
import { Document } from 'mongoose';

export interface CodeI extends Document {
  readonly _id: string;
  readonly logs: any;
}

但是当我从 mongo 获得结果时,它完全忽略了我界面中的内容。 (我使用 NestJs 作为框架)

 //constructor
   constructor(@InjectModel(Coupon.name) private couponModel: Model<CouponDocument>) {}

 // function
 async findOne(codeId: string): Promise<CodeI> {
    const coupon = await this.couponModel.findOne({ _id: codeId }).exec();
    if (!coupon) {
      throw new NotFoundException([`#${codeId} not found`]);
    }
    return coupon;
  }

【问题讨论】:

    标签: node.js typescript mongoose nestjs


    【解决方案1】:

    TypeScript 接口不能以这种方式工作。它们不能限制对象的字段,因为它们在运行时不存在,因此,我们不能使用它们来指导任何运行时行为。 TypeScript 接口仅对编译时类型检查有用。

    但是,就您而言,有两种方法可以实现预期的行为。

    1. 第一个是只选择您需要返回的必填字段(推荐)。

    在你的 findOne 中,你可以做这样的事情

    async findOne(codeId: string): Promise<CodeI> {
       const coupon = await this.couponModel.findOne({ _id: codeId }, '_id logs').exec();
       if (!coupon) {
         throw new NotFoundException([`#${codeId} not found`]);
       }
      return coupon;
    }
    

    在这里,如您所见,我向 findOne 函数传递了一个附加的字符串类型参数,该函数是投影,它将仅从对象中选择指定的字段。这不仅可以解决您的问题,还可以节省查询时间并提高查询性能。 Read more about findOne here.

    1. 另一种方法是创建一个 DTO,您可以在其中定义要从函数返回的字段。 像这样:

    // CouponDto.ts
    class CouponDto {
        public readonly _id: string;
        public readonly logs: any;
        constructor(data: CodeI) {
            this._id = data._id;
            this.logs = data.logs;
        }
    }

    然后,在您的服务文件中,您可以执行类似的操作

    return new CouponDto(coupon);
    

    (确保将函数的返回类型也更改为CouponDto

    您可以使用这两种方法中的任何一种。虽然我建议使用第一个,但这取决于您以及您希望如何构建您的项目。

    外部链接:

    【讨论】:

    • @dracarys_ 欢迎您的朋友。另外,如果您能接受它作为最佳答案,那就太好了。
    猜你喜欢
    • 2013-08-18
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2011-02-23
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多