Skip to content

Commit d28e5a0

Browse files
authored
Merge pull request #14892 from Automattic/vkarpov15/gh-12959
types: make __v a number, only set __v on top-level documents
2 parents 89d7b8b + 05a2234 commit d28e5a0

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed

test/types/document.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,3 +359,19 @@ function gh13738() {
359359
expectType<Date>(person.get('dob'));
360360
expectType<{ theme: string; alerts: { sms: boolean } }>(person.get('settings'));
361361
}
362+
363+
async function gh12959() {
364+
const subdocSchema = new Schema({ foo: { type: 'string', required: true } });
365+
366+
const schema = new Schema({
367+
subdocArray: { type: [subdocSchema], required: true }
368+
});
369+
370+
const Model = model('test', schema);
371+
372+
const doc = await Model.findById('id').orFail();
373+
expectType<Types.ObjectId>(doc._id);
374+
expectType<number | undefined>(doc.__v);
375+
376+
expectError(doc.subdocArray[0].__v);
377+
}

types/document.d.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,6 @@ declare module 'mongoose' {
2424
/** This documents _id. */
2525
_id: T;
2626

27-
/** This documents __v. */
28-
__v?: any;
29-
3027
/** Assert that a given path or paths is populated. Throws an error if not populated. */
3128
$assertPopulated<Paths = {}>(path: string | string[], values?: Partial<Paths>): Omit<this, keyof Paths> & Paths;
3229

types/index.d.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,10 @@ declare module 'mongoose' {
138138
? IfAny<U, T & { _id: Types.ObjectId }, T & Required<{ _id: U }>>
139139
: T & { _id: Types.ObjectId };
140140

141+
export type Default__v<T> = T extends { __v?: infer U }
142+
? T
143+
: T & { __v?: number };
144+
141145
/** Helper type for getting the hydrated document type from the raw document type. The hydrated document type is what `new MyModel()` returns. */
142146
export type HydratedDocument<
143147
DocType,
@@ -147,12 +151,12 @@ declare module 'mongoose' {
147151
DocType,
148152
any,
149153
TOverrides extends Record<string, never> ?
150-
Document<unknown, TQueryHelpers, DocType> & Require_id<DocType> :
154+
Document<unknown, TQueryHelpers, DocType> & Default__v<Require_id<DocType>> :
151155
IfAny<
152156
TOverrides,
153-
Document<unknown, TQueryHelpers, DocType> & Require_id<DocType>,
157+
Document<unknown, TQueryHelpers, DocType> & Default__v<Require_id<DocType>>,
154158
Document<unknown, TQueryHelpers, DocType> & MergeType<
155-
Require_id<DocType>,
159+
Default__v<Require_id<DocType>>,
156160
TOverrides
157161
>
158162
>

0 commit comments

Comments
 (0)