mongoose
mongoose copied to clipboard
Type of populated property
Is there an existing issue that is already proposing this?
- [X] I have searched the existing issues
Is your feature request related to a problem? Please describe it
Following the tutorial in the official NestJs documentation for MongoDB A populated property can be either a ObjectId or document so handling the populating property can be a little messy.
Also insertions and update with ObjectId seems to not be possible
Although this can be resolved by using union type between ObjectId and the entity, the Entity doesn't have _id in them, which although seems minor enough, _id of the populated document is cannot be fetched without bypassing the typescript type checking.
Describe the solution you'd like
Giving the populated Property it's own type seems to be a good starting point.
The following is how i would imagine it to be:
export type PopulatedEntity<T> = Types.ObjectId | (T & { _id: Types.ObjectId; });
This can be implemented in the @Schema entity as:
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' }) owner: PopulatedEntity<Owner>;
Teachability, documentation, adoption, migration strategy
No response
What is the motivation / use case for changing the behavior?
Following are the use cases where the default implementation cause an issue:
- manipulation(create/update) the populating property of the entity using only the ObjectId of the populated entity.
- fetching the populated property(ObjectId) when it is not populated.
- fetching the _id of the populated property when it is populated.