Skip to content

Commit

Permalink
fix(index.d.ts): allow strings for ObjectIds in nested properties
Browse files Browse the repository at this point in the history
Fix #10573
  • Loading branch information
vkarpov15 committed Aug 21, 2021
1 parent e90aab1 commit 6c36263
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
12 changes: 8 additions & 4 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1270,10 +1270,10 @@ declare module 'mongoose' {
/**
* Create a new schema
*/
constructor(definition?: SchemaDefinition<DocumentDefinition<SchemaDefinitionType>>, options?: SchemaOptions);
constructor(definition?: SchemaDefinition<LeanDocument<SchemaDefinitionType>>, options?: SchemaOptions);

/** Adds key path / schema type pairs to this schema. */
add(obj: SchemaDefinition<DocumentDefinition<SchemaDefinitionType>> | Schema, prefix?: string): this;
add(obj: SchemaDefinition<LeanDocument<SchemaDefinitionType>> | Schema, prefix?: string): this;

/**
* Array of child schemas (from document arrays and single nested subdocs)
Expand Down Expand Up @@ -2587,8 +2587,12 @@ declare module 'mongoose' {
export type UpdateQuery<T> = (_UpdateQuery<DocumentDefinition<T>> & mongodb.MatchKeysAndValues<DocumentDefinition<T>>);

type _AllowStringsForIds<T> = {
[K in keyof T]: [Extract<T[K], mongodb.ObjectId>] extends [never] ? T[K] : T[K] | string;
};
[K in keyof T]: [Extract<T[K], mongodb.ObjectId>] extends [never]
? T[K] extends TreatAsPrimitives
? T[K]
: _AllowStringsForIds<T[K]>
: T[K] | string;
};
export type DocumentDefinition<T> = _AllowStringsForIds<LeanDocument<T>>;

type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
Expand Down
5 changes: 4 additions & 1 deletion test/typescript/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface QueryHelpers {
const schema: Schema<ITest, Model<ITest, QueryHelpers>> = new Schema({
name: { type: 'String' },
tags: [String],
docs: [{ nested: { id: Number, tags: [String] } }],
docs: [{ _id: 'ObjectId', id: Number, tags: [String] }],
endDate: Date
});

Expand All @@ -22,6 +22,7 @@ schema.query.byName = function(name: string): QueryWithHelpers<any, ITest> {
};

interface ISubdoc extends Document {
myId?: Types.ObjectId;
id?: number;
tags?: string[];
}
Expand Down Expand Up @@ -89,6 +90,8 @@ Test.findOneAndUpdate({ name: 'test' }, [{ $set: { endDate: true } }]);

Test.findByIdAndUpdate({ name: 'test' }, { name: 'test2' }, (err, doc) => console.log(doc));

Test.findOneAndUpdate({ name: 'test' }, { 'docs.0.myId': '0'.repeat(24) });

const query: Query<ITest | null, ITest> = Test.findOne();
query instanceof Query;

Expand Down

0 comments on commit 6c36263

Please sign in to comment.