【发布时间】:2019-11-12 14:48:39
【问题描述】:
首先我想说这个问题类似于引用this one 的this 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.ObjectId 或UserDocument 上的User。所以我尝试将其定义为:
export interface LocationDocument extends Location, Document {
_id: Types.ObjectId
owner: User | Types.ObjectId;
}
但这会在编译器中引发一个错误,即 LocationDocument 错误地扩展了 Location。这是有道理的。有没有办法扩展用户类,但说所有者属性可以是用户类型(曾经由猫鼬填充)或 mongo 对象 ID(存储在数据库中)。
【问题讨论】:
标签: mongodb typescript mongoose nestjs