Skip to content

Commit 52b858e

Browse files
committed
feat: support dot-notation attributes in Filter
1 parent 6b3c161 commit 52b858e

File tree

3 files changed

+83
-12
lines changed

3 files changed

+83
-12
lines changed

src/index.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,9 @@ export type {
430430
KeysOfAType,
431431
KeysOfOtherType,
432432
IsAny,
433-
OneOrMore
433+
OneOrMore,
434+
Join,
435+
PropertyType,
436+
NestedPaths
434437
} from './mongo_types';
435438
export type { serialize, deserialize } from './bson';

src/mongo_types.ts

+43-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ export type WithoutId<TSchema> = Omit<TSchema, '_id'>;
5454

5555
/** A MongoDB filter can be some portion of the schema or a set of operators @public */
5656
export type Filter<TSchema> = {
57-
[P in keyof TSchema]?: Condition<TSchema[P]>;
57+
[P in Join<NestedPaths<TSchema>, '.'>]?: Condition<PropertyType<TSchema, P>>;
5858
} &
5959
RootFilterOperators<TSchema>;
6060

@@ -425,3 +425,45 @@ export class TypedEventEmitter<Events extends EventsDescription> extends EventEm
425425

426426
/** @public */
427427
export class CancellationToken extends TypedEventEmitter<{ cancel(): void }> {}
428+
429+
/**
430+
* Helper types for dot-notation filter attributes
431+
*/
432+
433+
/** @public */
434+
export type Join<T extends unknown[], D extends string> = T extends []
435+
? ''
436+
: T extends [string | number | boolean | bigint]
437+
? `${T[0]}`
438+
: T extends [string | number | boolean | bigint, ...infer R]
439+
? `${T[0]}${D}${Join<R, D>}`
440+
: string;
441+
442+
/** @public */
443+
export type PropertyType<T, P extends string> = string extends P
444+
? unknown
445+
: P extends keyof T
446+
? T[P]
447+
: P extends `${infer K}.${infer R}`
448+
? K extends keyof T
449+
? PropertyType<T[K], R>
450+
: unknown
451+
: unknown;
452+
453+
// We dont't support nested circular references
454+
/** @public */
455+
export type NestedPaths<T> = T extends
456+
| string
457+
| number
458+
| boolean
459+
| Date
460+
| ObjectId
461+
| Array<any>
462+
| ReadonlyArray<any>
463+
? []
464+
: // eslint-disable-next-line @typescript-eslint/ban-types
465+
T extends object
466+
? {
467+
[K in Extract<keyof T, string>]: [K, ...NestedPaths<T[K]>];
468+
}[Extract<keyof T, string>]
469+
: [];

test/types/community/collection/filterQuery.test-d.ts

+36-10
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ const db = client.db('test');
1515
* Test the generic Filter using collection.find<T>() method
1616
*/
1717

18+
interface HumanModel {
19+
_id: ObjectId;
20+
name: string;
21+
}
22+
1823
// a collection model for all possible MongoDB BSON types and TypeScript types
1924
interface PetModel {
2025
_id: ObjectId; // ObjectId field
@@ -23,14 +28,28 @@ interface PetModel {
2328
age: number; // number field
2429
type: 'dog' | 'cat' | 'fish'; // union field
2530
isCute: boolean; // boolean field
26-
bestFriend?: PetModel; // object field (Embedded/Nested Documents)
31+
bestFriend?: HumanModel; // object field (Embedded/Nested Documents)
2732
createdAt: Date; // date field
2833
treats: string[]; // array of string
2934
playTimePercent: Decimal128; // bson Decimal128 type
30-
readonly friends?: ReadonlyArray<PetModel>; // readonly array of objects
31-
playmates?: PetModel[]; // writable array of objects
35+
readonly friends?: ReadonlyArray<HumanModel>; // readonly array of objects
36+
playmates?: HumanModel[]; // writable array of objects
37+
// Object with multiple nested levels
38+
meta?: {
39+
updatedAt?: Date;
40+
deep?: {
41+
nested?: {
42+
level?: number;
43+
};
44+
};
45+
};
3246
}
3347

48+
const john = {
49+
_id: new ObjectId('577fa2d90c4cc47e31cf4b6a'),
50+
name: 'John'
51+
};
52+
3453
const spot = {
3554
_id: new ObjectId('577fa2d90c4cc47e31cf4b6f'),
3655
name: 'Spot',
@@ -78,14 +97,25 @@ expectNotType<Filter<PetModel>>({ age: [23, 43] });
7897

7998
/// it should query __nested document__ fields only by exact match
8099
// TODO: we currently cannot enforce field order but field order is important for mongo
81-
await collectionT.find({ bestFriend: spot }).toArray();
100+
await collectionT.find({ bestFriend: john }).toArray();
82101
/// nested documents query should contain all required fields
83-
expectNotType<Filter<PetModel>>({ bestFriend: { family: 'Andersons' } });
102+
expectNotType<Filter<PetModel>>({ bestFriend: { name: 'Andersons' } });
84103
/// it should not accept wrong types for nested document fields
85104
expectNotType<Filter<PetModel>>({ bestFriend: 21 });
86105
expectNotType<Filter<PetModel>>({ bestFriend: 'Andersons' });
87106
expectNotType<Filter<PetModel>>({ bestFriend: [spot] });
88-
expectNotType<Filter<PetModel>>({ bestFriend: [{ family: 'Andersons' }] });
107+
expectNotType<Filter<PetModel>>({ bestFriend: [{ name: 'Andersons' }] });
108+
109+
/// it should query __nested document__ fields using dot-notation
110+
collectionT.find({ 'meta.updatedAt': new Date() });
111+
collectionT.find({ 'meta.deep.nested.level': 123 });
112+
/// it should not accept wrong types for nested document fields
113+
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': 123 });
114+
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': true });
115+
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': 'now' });
116+
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': '123' });
117+
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': true });
118+
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': new Date() });
89119

90120
/// it should query __array__ fields by exact match
91121
await collectionT.find({ treats: ['kibble', 'bone'] }).toArray();
@@ -227,7 +257,3 @@ await collectionT.find({ playmates: { $elemMatch: { name: 'MrMeow' } } }).toArra
227257
expectNotType<Filter<PetModel>>({ name: { $all: ['world', 'world'] } });
228258
expectNotType<Filter<PetModel>>({ age: { $elemMatch: [1, 2] } });
229259
expectNotType<Filter<PetModel>>({ type: { $size: 2 } });
230-
231-
// dot key case that shows it is assignable even when the referenced key is the wrong type
232-
expectAssignable<Filter<PetModel>>({ 'bestFriend.name': 23 }); // using dot notation permits any type for the key
233-
expectNotType<Filter<PetModel>>({ bestFriend: { name: 23 } });

0 commit comments

Comments
 (0)