Skip to content

Commit

Permalink
Merge pull request #14892 from Automattic/vkarpov15/gh-12959
Browse files Browse the repository at this point in the history
types: make __v a number, only set __v on top-level documents
  • Loading branch information
vkarpov15 authored Sep 17, 2024
2 parents 89d7b8b + 05a2234 commit d28e5a0
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
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

0 comments on commit d28e5a0

Please sign in to comment.