In the beginning, I must mention that this query bears resemblance to this one which points to this particular question. My inquiry mirrors the second link with a noticeable distinction. I am endeavoring to expand a class produced by NestJS which delineates a property.
I'm employing NestJs in conjunction with the Schema-first technique detailed here. Furthermore, I am producing a file of classes based on my GraphQL Schema.
This is the Schema:
type Location {
name: String!
owner: User!
}
This generates the class:
export class Location {
name: string;
owner: User;
}
My aim now is to extend this class so that I avoid repetitiveness (bearing in mind there are numerous fields not displayed). Additionally, I intend to incorporate fields residing within a document but not present in the schema (like _id
in this instance). Below lies my LocationDocument along with my schema.
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',
}
);
The predicament arises now. The auto-generated Location
class from the GraphQL schema defines the owner
property as a User
type. However, in actuality, it is merely a mongodb id until populated by Mongoose. Therefore, it can be either a Types.ObjectId
or a User
inside a UserDocument
. Attempting to define it as follows results in an error:
export interface LocationDocument extends Location, Document {
_id: Types.ObjectId
owner: User | Types.ObjectId;
}
This triggers a compiler error stating that LocationDocument wrongly extends Location. This outcome is understandable. Is there any feasible method to broaden the User Class yet stipulate that the owner property may be either a User Type (post Mongoose population) or a mongo object ID (as preserved in the database)?