'Remove certain fields from the mongoose HydratedDocument

When we lean the documents, the id property is still included which is undefined and can cause unexpected errors.

To simplify this for my team, I want to remove the id field from the HydratedDocument in the custom types.

// @types/mongoose/index.d.ts

import 'mongoose';
import { HydratedDocument as _Hydra, Document as _Docu } from 'mongoose';

declare module 'mongoose' {
  export type HydratedDocument<T, TMethodsAndOverrides, TVirtuals> = Omit<_Hydra<T>, 'id' | '__v'>;
// tsconfig.json
"typeRoots": ["node_modules/@types", "@types"] 

It is still not working for me. When I import the typing and try to declare a variable. Then I found that actually id property is coming from Document class. Following is the updated typings

import 'mongoose';
import { HydratedDocument as _Hydra, Document as _Docu } from 'mongoose';

declare module 'mongoose' {
  export type HydratedDocument<T, TMethodsAndOverrides, TVirtuals> = Omit<_Hydra<T>, 'id' | '__v'>;
  export class Document implements Omit<_Docu, 'id'> {}
}

Unfortunately, this is also not working.

enter image description here



Solution 1:[1]

This can't be done. But there is a hack which I am currently using

import { Document } from 'mongoose';
import { ObjectId } from 'bson';

type _MongooseDoc<T> = Document<unknown, any, T> & T & { _id: ObjectId };

export type MongooseDoc<T> = Omit<_MongooseDoc<T>, '__v' | 'id'>;

export type MongooseRef<T> = MongooseDoc<T> | string | ObjectId;

export type MongooseLean<T> = Omit<MongooseDoc<T>, keyof Document<unknown, any, T>> & { _id: ObjectId };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tbhaxor