Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types: make __v a number, only set __v on top-level documents #14892

Merged
merged 3 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions test/types/document.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,19 @@ function gh13738() {
expectType<Date>(person.get('dob'));
expectType<{ theme: string; alerts: { sms: boolean } }>(person.get('settings'));
}

async function gh12959() {
const subdocSchema = new Schema({ foo: { type: 'string', required: true } });

const schema = new Schema({
subdocArray: { type: [subdocSchema], required: true }
});

const Model = model('test', schema);

const doc = await Model.findById('id').orFail();
expectType<Types.ObjectId>(doc._id);
expectType<number | undefined>(doc.__v);

expectError(doc.subdocArray[0].__v);
}
3 changes: 0 additions & 3 deletions types/document.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@ declare module 'mongoose' {
/** This documents _id. */
_id: T;

/** This documents __v. */
__v?: any;

/** Assert that a given path or paths is populated. Throws an error if not populated. */
$assertPopulated<Paths = {}>(path: string | string[], values?: Partial<Paths>): Omit<this, keyof Paths> & Paths;

Expand Down
10 changes: 7 additions & 3 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,10 @@ declare module 'mongoose' {
? IfAny<U, T & { _id: Types.ObjectId }, T & Required<{ _id: U }>>
: T & { _id: Types.ObjectId };

export type Default__v<T> = T extends { __v?: infer U }
? T
: T & { __v?: number };

/** Helper type for getting the hydrated document type from the raw document type. The hydrated document type is what `new MyModel()` returns. */
export type HydratedDocument<
DocType,
Expand All @@ -147,12 +151,12 @@ declare module 'mongoose' {
DocType,
any,
TOverrides extends Record<string, never> ?
Document<unknown, TQueryHelpers, DocType> & Require_id<DocType> :
Document<unknown, TQueryHelpers, DocType> & Default__v<Require_id<DocType>> :
IfAny<
TOverrides,
Document<unknown, TQueryHelpers, DocType> & Require_id<DocType>,
Document<unknown, TQueryHelpers, DocType> & Default__v<Require_id<DocType>>,
Document<unknown, TQueryHelpers, DocType> & MergeType<
Require_id<DocType>,
Default__v<Require_id<DocType>>,
TOverrides
>
>
Expand Down