【问题标题】:Populate a query in Mongoose with Schema First approach and NestJS使用 Schema First 方法和 NestJS 在 Mongoose 中填充查询
【发布时间】:2019-11-12 14:48:39
【问题描述】:

首先我想说这个问题类似于引用this onethis one。我有与第二个链接完全相同的问题,除了一个显着的区别。我正在尝试扩展由 NestJS 生成的定义属性的类。

我正在使用 NestJs 和 here 发现的 Schema first 方法。我还在基于我的 GraphQL Schema 生成一个类文件。

这是架构:

type Location {
  name: String!
  owner: User!
}

生成类:

export class Location {
    name: string;
    owner: User;
}

现在,我想扩展这个类,这样我就不必重复数据(还有很多字段没有显示)。我还想添加存在于文档中但不在架构中的字段(在此示例中为_id)。这是我的 LocationDocument 和我的架构。

export interface LocationDocument extends Location, Document {
  _id: Types.ObjectId
}

export const LocationSchema: Schema = new Schema(
  {
    name: {
      type: String,
      required: true,
    },
    owner: {
      type: Types.ObjectId,
      ref: 'User',
    }
);

现在这是我的问题。从 GraphQL 模式生成的 Location 类将 owner 属性定义为 User 类型。但实际上它只是一个 mongodb id,直到它被 Mongoose 填充。所以它可能是Types.ObjectIdUserDocument 上的User。所以我尝试将其定义为:

export interface LocationDocument extends Location, Document {
  _id: Types.ObjectId
  owner: User | Types.ObjectId;
}

但这会在编译器中引发一个错误,即 LocationDocument 错误地扩展了 Location。这是有道理的。有没有办法扩展用户类,但说所有者属性可以是用户类型(曾经由猫鼬填充)或 mongo 对象 ID(存储在数据库中)。

【问题讨论】:

    标签: mongodb typescript mongoose nestjs


    【解决方案1】:

    我决定拥有一个可以同时是两种类型的属性,虽然使用 Mongoose 和 JS 很容易,但不是类型化的方式。在我的架构中,我有一个用户类型的所有者。在我的数据库和扩展它的文档中,我有一个 OwnerId。所以对于访问 API 的人来说,他们并不关心关系的 ownerId。但在我的解析器中,我使用了 ID。一个是 Mongo ID 类型,另一个是 User 类型。

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 2017-12-23
      • 2012-07-03
      相关资源
      最近更新 更多