Skip to content

Commit da0454a

Browse files
committed
feat: support dot-notation attributes in Filter
1 parent fa2f8d0 commit da0454a

File tree

3 files changed

+90
-12
lines changed

3 files changed

+90
-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

+46-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export type WithoutId<TSchema> = Omit<TSchema, '_id'>;
5656

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

6262
/** @public */
@@ -422,3 +422,48 @@ export class TypedEventEmitter<Events extends EventsDescription> extends EventEm
422422

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

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

+40-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,29 @@ 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+
collectionT.find({ 'friends.0.name': 'John' });
113+
collectionT.find({ 'playmates.0.name': 'John' });
114+
/// it should not accept wrong types for nested document fields
115+
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': 123 });
116+
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': true });
117+
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': 'now' });
118+
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': '123' });
119+
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': true });
120+
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': new Date() });
121+
expectNotType<Filter<PetModel>>({ 'friends.0.name': 123 });
122+
expectNotType<Filter<PetModel>>({ 'playmates.0.name': 123 });
89123

90124
/// it should query __array__ fields by exact match
91125
await collectionT.find({ treats: ['kibble', 'bone'] }).toArray();
@@ -227,7 +261,3 @@ await collectionT.find({ playmates: { $elemMatch: { name: 'MrMeow' } } }).toArra
227261
expectNotType<Filter<PetModel>>({ name: { $all: ['world', 'world'] } });
228262
expectNotType<Filter<PetModel>>({ age: { $elemMatch: [1, 2] } });
229263
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)