-
-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathqueries.test.ts
More file actions
920 lines (759 loc) · 29.1 KB
/
queries.test.ts
File metadata and controls
920 lines (759 loc) · 29.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
import mongoose, {
HydratedDocument,
Schema,
model,
Document,
Types,
Query,
Model,
QueryWithHelpers,
PopulatedDoc,
UpdateQuery,
UpdateQueryKnownOnly,
InferRawDocType,
InferSchemaType,
ProjectionFields,
QueryOptions,
ProjectionType,
QueryFilter
} from 'mongoose';
import mongodb from 'mongodb';
import { ModifyResult, ObjectId } from 'mongodb';
import { autoTypedModel } from './models.test';
import { ExpectAssignable, ExpectType } from './util/assertions';
interface QueryHelpers {
_byName(this: QueryWithHelpers<any, ITest, QueryHelpers>, name: string): QueryWithHelpers<Array<ITest>, ITest, QueryHelpers>;
byName(this: QueryWithHelpers<any, ITest, QueryHelpers>, name: string): QueryWithHelpers<Array<ITest>, ITest, QueryHelpers>;
}
const childSchema = new Schema({ name: String });
const ChildModel = model<Child>('Child', childSchema);
const schema: Schema<ITest, Model<ITest, QueryHelpers>, {}, QueryHelpers> = new Schema({
name: { type: 'String' },
tags: [String],
child: { type: 'ObjectId', ref: 'Child' },
docs: [{ _id: 'ObjectId', id: Number, tags: [String] }],
endDate: Date
});
schema.query._byName = function(name: string): QueryWithHelpers<ITest[], ITest, QueryHelpers> {
return this.find({ name });
};
schema.query.byName = function(name: string): QueryWithHelpers<ITest[], ITest, QueryHelpers> {
// @ts-expect-error Property 'notAQueryHelper' does not exist on type
this.notAQueryHelper();
return this._byName(name);
};
interface Child {
name: string;
}
interface ISubdoc {
myId?: Types.ObjectId;
id?: number;
tags?: string[];
profiles: {
name?: string
}
}
interface ITest {
name?: string;
age?: number;
parent?: Types.ObjectId;
child?: PopulatedDoc<HydratedDocument<Child>>,
tags?: string[];
docs?: ISubdoc[];
endDate?: Date;
}
type X = mongoose.WithLevel1NestedPaths<ITest>;
ExpectType<number | undefined>({} as X['docs.id']);
const Test = model<ITest, Model<ITest, QueryHelpers>>('Test', schema);
Test.find({}, {}, { populate: { path: 'child', model: ChildModel, match: true } }).exec().then((res: Array<ITest>) => console.log(res));
Test.find().byName('test').byName('test2').orFail().exec().then(console.log);
Test.countDocuments({ name: /Test/ }).exec().then((res: number) => console.log(res));
Test.findOne({ 'docs.id': 42 }).exec().then(console.log);
// ObjectId casting
Test.find({ parent: new Types.ObjectId('0'.repeat(24)) });
Test.find({ parent: '0'.repeat(24) });
Test.find({ parent: { $in: ['0'.repeat(24)] } });
// Operators
Test.find({ name: { $in: ['Test'] } }).exec().then((res: Array<ITest>) => console.log(res));
Test.find({ tags: 'test' }).exec();
Test.find({ tags: { $in: ['test'] } }).exec();
Test.find({ tags: /test/ }).exec();
Test.find({ tags: { $in: [/test/] } }).exec();
// Implicit `$in`
Test.find({ name: ['Test1', 'Test2'] }).exec();
// Implicit `$in` for regex string
Test.find({ name: [/Test1/, /Test2/] });
Test.find({ name: { $gte: 'Test' } }, null, { collation: { locale: 'en-us' } }).exec().
then((res: Array<ITest>) => console.log(res[0].name));
Test.findOne().orFail(new Error('bar')).then((doc: ITest | null) => console.log('Found! ' + doc));
Test.distinct('name').exec().then((res: Array<any>) => console.log(res[0]));
Test.distinct('name', {}, { collation: { locale: 'en', strength: 2 } }).exec().then((res: Array<any>) => console.log(res[0]));
Test.findOneAndUpdate({ name: 'test' }, { name: 'test2' }).exec().then((res: ITest | null) => console.log(res));
Test.findOneAndUpdate({ name: 'test' }, { name: 'test2' }).then((res: ITest | null) => console.log(res));
Test.findOneAndUpdate({ name: 'test' }, { $set: { name: 'test2' } }).then((res: ITest | null) => console.log(res));
Test.findOneAndUpdate({ name: 'test' }, { $inc: { age: 2 } }).then((res: ITest | null) => console.log(res));
Test.findOneAndUpdate({ name: 'test' }, { name: 'test3' }, { upsert: true, new: true }).then((res: ITest) => {
res.name = 'test4';
});
Test.findOneAndUpdate({ name: 'test' }, { name: 'test3' }, { upsert: true, returnOriginal: false }).then((res: ITest) => {
res.name = 'test4';
});
Test.findOneAndUpdate({ name: 'test' }, { name: 'test3' }, { includeResultMetadata: true }).then((res: any) => {
console.log(res.ok);
});
Test.findOneAndUpdate({ name: 'test' }, { name: 'test3' }, { new: true, upsert: true, includeResultMetadata: true }).then((res: any) => {
console.log(res.ok);
});
Test.findOneAndReplace({ name: 'test' }, { _id: new Types.ObjectId(), name: 'test2' }).exec().then((res: ITest | null) => console.log(res));
Test.findOneAndUpdate({ name: 'test' }, { $addToSet: { tags: 'each' } });
Test.findOneAndUpdate({ name: 'test' }, { $push: { tags: 'each' } });
Test.findOneAndUpdate({ name: 'test' }, { $pull: { docs: { 'nested.id': 1 } } });
Test.findOneAndUpdate({ name: 'test', 'docs.id': 1 }, { $pull: { 'docs.$.tags': 'foo' } });
const update = Math.random() > 0.5 ? { $unset: { 'docs.0': 1 } } : { age: 55 };
Test.findOneAndUpdate({ name: 'test' }, update);
Test.findOneAndUpdate({ name: 'test' }, { $currentDate: { endDate: true } });
Test.findOneAndUpdate({ name: 'test' }, [{ $set: { endDate: true } }]);
Test.findByIdAndUpdate({ name: 'test' }, { name: 'test2' }, (err: any, doc: any) => console.log(doc));
Test.findOneAndUpdate({ name: 'test' }, { 'docs.0.myId': '0'.repeat(24) });
// Chaining
Test.findOne().where({ name: 'test' });
Test.where().find({ name: 'test' });
// Projection
const p0: Record<string, number> = Test.find().projection({
age: true,
parent: 1,
'docs.id': 1
});
const p1: Record<string, number> = Test.find().projection('age docs.id');
const p2: Record<string, number> | null = Test.find().projection();
const p3: null = Test.find().projection(null);
// @ts-expect-error No overload matches this call.
Test.find({ }, { name: 'ss' }); // Only 0 and 1 are allowed
Test.find({}, { name: 3 });
Test.find({}, { name: true, age: false, endDate: true, tags: 1 });
Test.find({}, { name: true, age: false, endDate: true });
Test.find({}, { name: false, age: false, tags: false, child: { name: false }, docs: { myId: false, id: true } });
// @ts-expect-error No overload matches this call.
Test.find({}, { tags: { something: 1 } }); // Array of strings or numbers should only be allowed to be a boolean or 1 and 0
Test.find({}, { name: true, age: true, endDate: true, tags: 1, child: { name: true }, docs: { myId: true, id: true } }); // This should be allowed
Test.find({}, { name: 1, age: 1, endDate: 1, tags: 1, child: { name: 1 }, docs: { myId: 1, id: 1 } }); // This should be allowed
Test.find({}, { _id: 0, name: 1, age: 1, endDate: 1, tags: 1, child: 1, docs: 1 }); // _id is an exception and should be allowed to be excluded
Test.find({}, { name: 0, age: 0, endDate: 0, tags: 0, child: 0, docs: 0 }); // This should be allowed
Test.find({}, { name: 0, age: 0, endDate: 0, tags: 0, child: { name: 0 }, docs: { myId: 0, id: 0 } }); // This should be allowed
Test.find({}, { name: 1, age: 1, _id: 0 }); // This should be allowed since _id is an exception
Test.find({}, { someOtherField: 1 }); // This should be allowed since it's not a field in the schema
// @ts-expect-error No overload matches this call.
Test.find({}, { name: { $slice: 1 } }); // $slice should only be allowed on arrays
Test.find({}, { tags: { $slice: 1 } }); // $slice should be allowed on arrays
Test.find({}, { tags: { $slice: [1, 2] } }); // $slice with the format of [ <number to skip>, <number to return> ] should also be allowed on arrays
// @ts-expect-error No overload matches this call.
Test.find({}, { age: { $elemMatch: {} } }); // $elemMatch should not be allowed on non arrays
Test.find({}, { docs: { $elemMatch: { id: 'aa' } } }); // $elemMatch should be allowed on arrays
// @ts-expect-error No overload matches this call.
Test.find({}, { tags: { $slice: 1, $elemMatch: {} } }); // $elemMatch and $slice should not be allowed together
Test.find({}, { age: 1, tags: { $slice: 5 } }); // $slice should be allowed in inclusion projection
Test.find({}, { age: 0, tags: { $slice: 5 } }); // $slice should be allowed in exclusion projection
Test.find({}, { age: 1, tags: { $elemMatch: {} } }); // $elemMatch should be allowed in inclusion projection
Test.find({}, { age: 0, tags: { $elemMatch: {} } }); // $elemMatch should be allowed in exclusion projection
// @ts-expect-error No overload matches this call.
Test.find({}, { 'docs.id': 'taco' }); // Dot notation should be allowed and does not accept any
// @ts-expect-error No overload matches this call.
Test.find({}, { docs: { id: '1' } }); // Dot notation should be able to use a combination with objects
Test.find({}, { docs: { id: false } }); // Dot notation should be allowed with valid values - should correctly handle arrays
Test.find({}, { docs: { id: true } }); // Dot notation should be allowed with valid values - should correctly handle arrays
Test.find({ docs: { $elemMatch: { id: 1 } } }, { 'docs.$': 1 }); // $ projection should be allowed
Test.find({}, { child: 1 }); // Dot notation should be able to use a combination with objects
// Test.find({}, { 'docs.profiles': { name: 1 } }); // 3 levels deep not supported
// @ts-expect-error No overload matches this call.
Test.find({}, { 'docs.profiles': { name: 'aa' } }); // should support a combination of dot notation and objects
// @ts-expect-error No overload matches this call.
Test.find({}, { endDate: { toString: 1 } }); // should not allow projecting inherited methods in nested objects
// @ts-expect-error No overload matches this call.
Test.find({}, { tags: { trim: 1 } }); // should not allow projecting inherited methods in nested objects
// @ts-expect-error No overload matches this call.
Test.find({}, { child: { toJSON: 1 } }); // should not allow projecting inherited methods in nested objects
Test.find({}, { age: 1, _id: 0 });
Test.find({}, { name: 0, age: 0, _id: 1 });
// Manual Casting using ProjectionType
Test.find({}, { docs: { unknownParams: 1 } } as ProjectionType<ITest>);
// Sorting
Test.find().sort();
Test.find().sort('-name');
Test.find().sort({ name: -1 });
Test.find().sort({ name: 'ascending' });
Test.find().sort(undefined);
Test.find().sort(null);
Test.find().sort([['key', 'ascending']]);
Test.find().sort([['key1', 'ascending'], ['key2', 'descending']]);
// @ts-expect-error Argument of type '{ name: 2; }' is not assignable
Test.find().sort({ name: 2 });
// @ts-expect-error Argument of type '{ name: "invalidSortOrder"; }' is not assignable
Test.find().sort({ name: 'invalidSortOrder' });
// @ts-expect-error Type '"invalid"' is not assignable to type 'SortOrder'.
Test.find().sort([['key', 'invalid']]);
// @ts-expect-error Type 'false' is not assignable to type 'SortOrder'.
Test.find().sort([['key', false]]);
// @ts-expect-error Type 'string' is not assignable to type '[string, SortOrder]'.
Test.find().sort(['invalid']);
// Super generic query
function testGenericQuery(): void {
interface CommonInterface<T> {
something: string;
content: T;
}
async function findSomething<T>(model: Model<CommonInterface<T>>): Promise<CommonInterface<T>> {
return model.findOne({ something: 'test' } as mongoose.QueryFilter<CommonInterface<T>>).orFail().exec();
}
}
function eachAsync(): void {
Test.find().cursor().eachAsync((doc) => {
ExpectType<HydratedDocument<ITest, {}, QueryHelpers>>(doc);
});
Test.find().cursor().eachAsync((docs) => {
ExpectType<HydratedDocument<ITest, {}, QueryHelpers>[]>(docs);
}, { batchSize: 2 });
}
async function gh10617(): Promise<void> {
interface IDBModel extends Document {
date: Date; // date created
_tags: any[];
}
const schema = new Schema({
date: { type: Date, default: Date.now }, // date created
_tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
});
const DBModel: Model<IDBModel> = model<IDBModel>('Meep', schema);
await DBModel.findOne({});
}
function gh10757() {
enum MyEnum {
VALUE1,
VALUE2,
VALUE3
}
interface MyClass {
status: MyEnum;
}
type MyClassDocument = MyClass & Document;
const test: QueryFilter<MyClass> = { status: { $in: [MyEnum.VALUE1, MyEnum.VALUE2] } };
}
function gh10857() {
type MyUnion = 'VALUE1' | 'VALUE2';
interface MyClass {
status: MyUnion;
}
type MyClassDocument = MyClass & Document;
const test: QueryFilter<MyClass> = { status: { $in: ['VALUE1', 'VALUE2'] } };
}
function gh10786() {
interface User {
phone?: string;
name?: string
}
const updateQuery: UpdateQuery<User> = { name: 'John' };
if (true) {
updateQuery.phone = 'XXXX';
}
}
async function gh11156(): Promise<void> {
interface IUser {
name: string;
age: number;
}
const schema = new Schema<IUser>({
name: String,
age: Number
});
const User: Model<IUser> = model<IUser>('User', schema);
const doc = await User.findOne<Pick<IUser, 'name'>>({}).orFail();
ExpectType<{ name: string }>(doc);
}
async function gh11041(): Promise<void> {
interface User {
name: string;
email: string;
avatar?: string;
}
// 2. Create a Schema corresponding to the document interface.
const schema = new Schema<User>({
name: { type: String, required: true },
email: { type: String, required: true },
avatar: String
});
// 3. Create a Model.
const MyModel = model<User>('User', schema);
ExpectType<HydratedDocument<User> | null>(await MyModel.findOne({}).populate('someField').exec());
}
async function gh11306(): Promise<void> {
interface User {
name: string;
email: string;
avatar?: string;
}
// 2. Create a Schema corresponding to the document interface.
const schema = new Schema<User>({
name: { type: String, required: true },
email: { type: String, required: true },
avatar: String
});
// 3. Create a Model.
const MyModel = model<User>('User', schema);
ExpectType<unknown[]>(await MyModel.distinct('notThereInSchema'));
ExpectType<string[]>(await MyModel.distinct('name'));
}
function autoTypedQuery() {
const AutoTypedModel = autoTypedModel();
const query = AutoTypedModel.find();
ExpectType<typeof query>(AutoTypedModel.find().byUserName(''));
}
function gh11964() {
class Repository<T extends { id: string }> {
find(id: string) {
const idCondition: mongodb.Condition<T['id']> = id as mongodb.Condition<T['id']>;
// `as` is necessary because `T` can be `{ id: never }`,
// so we need to explicitly coerce
const filter: QueryFilter<T> = { id } as QueryFilter<T>;
}
}
}
function gh14397() {
type Condition<T> = mongodb.Condition<T>; // redefined here because it's not exported by mongoose
type WithId<T extends object> = T & { id: string };
type TestUser = {
name: string;
age: number;
};
const id = 'Test Id';
let idCondition: Condition<WithId<TestUser>['id']>;
let filter: QueryFilter<WithId<TestUser>>;
ExpectAssignable<typeof idCondition>()(id);
ExpectAssignable<typeof filter>()({ id });
}
function gh12091() {
interface IUser{
friendsNames: string[];
}
const userSchema = new Schema<IUser>({
friendsNames: [String]
});
const update: UpdateQuery<IUser> = { $addToSet: { friendsNames: 'John Doe' } };
if (!update?.$addToSet) {
return;
}
update.$addToSet.friendsNames = 'Jane Doe';
}
function gh12142() {
const schema = new Schema({ name: String, comments: [{ text: String }] });
const Test = model('Test', schema);
Test.updateOne(
{ _id: new Types.ObjectId() },
{
$pull: { comments: new Types.ObjectId() }
}
);
}
async function gh12342_manual() {
interface Project {
name?: string, stars?: number
}
interface ProjectQueryHelpers {
byName(name: string): QueryWithHelpers<
HydratedDocument<Project>[],
HydratedDocument<Project>,
ProjectQueryHelpers
>
}
type ProjectModelType = Model<Project, ProjectQueryHelpers>;
const ProjectSchema = new Schema<
Project,
Model<Project, ProjectQueryHelpers>,
{},
ProjectQueryHelpers
>({
name: String,
stars: Number
});
ProjectSchema.query.byName = function byName(
this: QueryWithHelpers<any, HydratedDocument<Project>, ProjectQueryHelpers>,
name: string
) {
return this.find({ name: name });
};
// 2nd param to `model()` is the Model class to return.
const ProjectModel = model<Project, ProjectModelType>('Project', schema);
ExpectType<HydratedDocument<Project>[]>(
await ProjectModel.findOne().where('stars').gt(1000).byName('mongoose')
);
}
async function gh12342_auto() {
interface Project {
name?: string | null,
stars?: number | null
}
const ProjectSchema = new Schema({
name: String,
stars: Number
}, {
query: {
byName(name: string) {
return this.find({ name });
}
}
});
const ProjectModel = model('Project', ProjectSchema);
ExpectAssignable<HydratedDocument<Project>[]>()(
await ProjectModel.findOne().where('stars').gt(1000).byName('mongoose')
);
}
async function gh11602(): Promise<void> {
const query = Test.findOne();
query instanceof Query;
const ModelType = model<ITest>('foo', schema);
const updateResult = await ModelType.findOneAndUpdate(query, { $inc: { occurence: 1 } }, {
upsert: true,
returnDocument: 'after',
includeResultMetadata: true
});
// @ts-expect-error Property 'modifiedCount' does not exist on type
updateResult.lastErrorObject?.modifiedCount;
ExpectType<boolean | undefined>(updateResult.lastErrorObject?.updatedExisting);
ExpectType<ObjectId | undefined>(updateResult.lastErrorObject?.upserted);
ModelType.findOneAndUpdate({}, {}, { returnDocument: 'before' });
ModelType.findOneAndUpdate({}, {}, { returnDocument: 'after' });
ModelType.findOneAndUpdate({}, {}, { returnDocument: undefined });
ModelType.findOneAndUpdate({}, {}, {});
// @ts-expect-error No overload matches this call.
ModelType.findOneAndUpdate({}, {}, { returnDocument: 'not-before-or-after' }); // returnDocument should be 'before' or 'after'
}
async function gh13142() {
const BlogSchema = new Schema({ title: String });
type Blog = InferSchemaType<typeof BlogSchema>;
const BlogModel = model<Blog>('Blog', BlogSchema);
class BlogRepository {
private readonly blogModel: Model<Blog>;
constructor() {
this.blogModel = BlogModel;
}
findOne<
Projection extends ProjectionFields<Blog>,
Options extends QueryOptions<Blog>
>(
filter: QueryFilter<mongoose.WithLevel1NestedPaths<Blog>>,
projection: Projection,
options: Options
): Promise<
Options['lean'] extends true
? Pick<Blog, Extract<keyof Projection, keyof Blog>> | null
: HydratedDocument<Pick<Blog, Extract<keyof Projection, keyof Blog>>> | null
> {
return this.blogModel.findOne(filter, projection, options);
}
}
const blogRepository = new BlogRepository();
const blog = await blogRepository.findOne(
{ title: 'test' },
{ content: 1 },
{ lean: true }
);
if (!blog) return;
ExpectType<Pick<Blog, Extract<keyof { content: 1 }, keyof Blog>>>(blog);
}
async function gh13224() {
const userSchema = new Schema({ name: String, age: Number });
const UserModel = model('User', userSchema);
const u1 = await UserModel.findOne().select(['name']).orFail();
ExpectType<string | undefined | null>(u1.name);
ExpectType<number | undefined | null>(u1.age);
ExpectAssignable<Function>()(u1.toObject);
const u2 = await UserModel.findOne().select<{ name?: string }>(['name']).orFail();
ExpectType<string | undefined>(u2.name);
// @ts-expect-error Property 'age' does not exist on type
u2.age;
ExpectAssignable<Function>()(u2.toObject);
const users = await UserModel.find().select<{ name?: string }>(['name']);
const u3 = users[0];
ExpectType<string | undefined>(u3!.name);
// @ts-expect-error Property 'age' does not exist on type
u3!.age;
ExpectAssignable<Function>()(u3.toObject);
// @ts-expect-error Type '{ notInSchema: string; }' has no properties in common with type '{ name?: any; age?: any; _id?: any; __v?: any; }'.
await UserModel.findOne().select<{ notInSchema: string }>(['name']).orFail();
}
function gh13630() {
interface User {
phone?: string;
name?: string;
nested?: {
test?: string;
}
}
ExpectAssignable<UpdateQueryKnownOnly<User>>()({ $set: { name: 'John' } });
ExpectAssignable<UpdateQueryKnownOnly<User>>()({ $unset: { phone: 'test' } });
ExpectAssignable<UpdateQueryKnownOnly<User>>()({ $set: { nested: { test: 'foo' } } });
// @ts-expect-error 'namee' does not exist in type 'AnyKeys<User>'.
const q1: UpdateQueryKnownOnly<User> = { $set: { namee: 'foo' } };
// @ts-expect-error ''nested.test'' does not exist in type 'AnyKeys<User>'.
const q2: UpdateQueryKnownOnly<User> = { $set: { 'nested.test': 'foo' } };
const x: UpdateQueryKnownOnly<User> = { $set: { name: 'John' } };
ExpectAssignable<UpdateQuery<User>>()(x);
}
async function gh14190() {
const userSchema = new Schema({ name: String, age: Number });
const UserModel = model('User', userSchema);
const doc = await UserModel.findByIdAndDelete('0'.repeat(24));
ExpectType<ReturnType<(typeof UserModel)['hydrate']> | null>(doc);
const res = await UserModel.findByIdAndDelete(
'0'.repeat(24),
{ includeResultMetadata: true }
);
ExpectAssignable<
ModifyResult<ReturnType<(typeof UserModel)['hydrate']>>
>()(res);
const res2 = await UserModel.find().findByIdAndDelete(
'0'.repeat(24),
{ includeResultMetadata: true }
);
ExpectAssignable<
ModifyResult<ReturnType<(typeof UserModel)['hydrate']>>
>()(res2);
}
function mongooseQueryOptions() {
const userSchema = new Schema({ name: String, age: Number });
const UserModel = model('User', userSchema);
UserModel.updateOne(
{ name: 'bar' },
{ name: 'baz' },
{
context: 'query',
multipleCastError: true,
overwriteDiscriminatorKey: true,
runValidators: true,
sanitizeProjection: true,
sanitizeFilter: true,
setDefaultsOnInsert: true,
strict: true,
strictQuery: 'throw',
timestamps: false,
translateAliases: false
}
);
UserModel.findOne({}, null, {
lean: true,
populate: 'test'
});
}
function gh14473() {
class AbstractSchema {
_id: any;
createdAt: Date;
updatedAt: Date;
deletedAt: Date;
constructor() {
this._id = 4;
this.createdAt = new Date();
this.updatedAt = new Date();
this.deletedAt = new Date();
}
}
const generateExists = <D extends AbstractSchema = AbstractSchema>() => {
const query: QueryFilter<D> = { deletedAt: { $ne: null } };
const query2: QueryFilter<D> = { deletedAt: { $lt: new Date() } } as QueryFilter<D>;
};
}
async function gh14525() {
type BeAnObject = Record<string, any>;
interface SomeDoc {
something: string;
func(this: TestDoc): string;
}
interface PluginExtras {
pfunc(): number;
}
type TestDoc = Document<unknown, BeAnObject, SomeDoc> & PluginExtras;
type ModelType = Model<SomeDoc, BeAnObject, PluginExtras, BeAnObject>;
const doc = await ({} as ModelType).findOne({}).populate('test').orFail().exec();
doc.func();
let doc2 = await ({} as ModelType).create({});
doc2 = await ({} as ModelType).findOne({}).populate('test').orFail().exec();
}
async function gh14545() {
type Test = {
_id: Types.ObjectId;
prop: string;
another: string;
createdAt: number;
updatedAt: number;
};
const schema = new Schema<Test>({
prop: { type: String },
another: { type: String },
createdAt: { type: Number },
updatedAt: { type: Number }
});
type TestDocument = HydratedDocument<Test>;
type TestModel = Model<Test, {}, {}, {}, TestDocument>;
type SlimTest = Pick<Test, '_id' | 'prop'>;
type SlimTestDocument = HydratedDocument<SlimTest>;
const M = model<Test, TestModel>('Test', schema);
const myDocs = await M.find({}).exec();
const myDoc = await M.findOne({}).exec();
const myProjections = await M.find({}).select<SlimTest>({ prop: 1 }).exec();
ExpectType<SlimTestDocument[]>(myProjections);
const myProjection = await M.findOne({}).select<SlimTest>({ prop: 1 }).exec();
ExpectType<SlimTestDocument | null>(myProjection);
}
function gh14841() {
const filter: QueryFilter<{ owners: string[] }> = {
$expr: { $lt: [{ $size: '$owners' }, 10] }
};
}
function gh14510() {
// From https://stackoverflow.com/questions/56505560/how-to-fix-ts2322-could-be-instantiated-with-a-different-subtype-of-constraint:
// "Never assign a concrete type to a generic type parameter, consider it as read-only!"
// This function is generally something you shouldn't do in TypeScript, can work around it with `as` though.
function findById<ModelType extends {_id: Types.ObjectId | string}>(model: Model<ModelType>, _id: Types.ObjectId | string) {
return model.find({ _id: _id } as QueryFilter<ModelType>);
}
}
async function gh15526() {
const userSchemaDefinition = { name: String, age: Number } as const;
const UserModel = model('User', new Schema(userSchemaDefinition));
type UserType = InferRawDocType<typeof userSchemaDefinition>;
const selection = ['name'] as const satisfies readonly (keyof UserType)[];
type SelectType = Pick<UserType, (typeof selection)[number]>;
const u1 = await UserModel.findOne()
.select<SelectType>(selection)
.orFail();
ExpectType<string | undefined | null>(u1.name);
// @ts-expect-error Property 'age' does not exist on type
u1.age;
}
async function gh14173() {
const userSchema = new Schema({
name: String,
account: {
amount: Number,
owner: { type: String, default: () => 'OWNER' },
taxIds: [Number]
}
});
const User = model('User', userSchema);
const { _id } = await User.create({
name: 'test',
account: {
amount: 25,
owner: 'test',
taxIds: [42]
}
});
const doc = await User
.findOne({ _id }, { name: 1, account: { amount: 1 } })
.orFail();
}
async function gh3230() {
const Test = model(
'Test',
new Schema({ name: String, arr: [{ testRef: { type: 'ObjectId', ref: 'Test2' } }] })
);
const schema = new Schema({ name: String });
const Test2 = model('Test2', schema);
const D = Test2.discriminator('D', new Schema({ prop: String }));
await Test.deleteMany({});
await Test2.deleteMany({});
const { _id } = await D.create({ name: 'foo', prop: 'bar' });
const test = await Test.create({ name: 'test', arr: [{ testRef: _id }] });
console.log(await Test.findById(test._id).populate('arr.testRef', { name: 1, prop: 1, _id: 0, __t: 0 }));
}
async function gh12064() {
const schema = new Schema({
subdoc: new Schema({
subdocProp: Number
}),
nested: {
nestedProp: String
},
documentArray: [{ documentArrayProp: Boolean }]
});
const TestModel = model('Model', schema);
await TestModel.findOne({ 'subdoc.subdocProp': { $gt: 0 }, 'nested.nestedProp': { $in: ['foo', 'bar'] }, 'documentArray.documentArrayProp': { $ne: true } });
// @ts-expect-error No overload matches this call.
TestModel.findOne({ 'subdoc.subdocProp': 'taco tuesday' });
// @ts-expect-error No overload matches this call.
TestModel.findOne({ 'nested.nestedProp': true });
// @ts-expect-error No overload matches this call.
TestModel.findOne({ 'documentArray.documentArrayProp': 'taco' });
}
function gh15671() {
interface DefaultQuery {
search?: string;
}
type QueryFeaturesProps = {
params: Partial<DefaultQuery>;
};
const queryFeatures = async <T, R, TQueryOp>(
query: mongoose.Query<R, T, object, T, TQueryOp>,
{ params }: QueryFeaturesProps
): Promise<{ content: mongoose.GetLeanResultType<T, R, TQueryOp>; result?: number }> => {
if (params.search) {
query.find({
$text: {
$search: params.search
}
});
}
const content = await query.lean().orFail().exec();
return {
content
};
};
}
async function gh15779() {
type Entity = {
id: string;
age: number;
name: string;
};
function getV8FilterQuery(filter: QueryFilter<Entity>): QueryFilter<Entity> {
return { ...filter, deletedAt: null };
}
const v8Filter = getV8FilterQuery({ age: { $gt: 18 } });
v8Filter.name = 'test';
type AgeType = typeof v8Filter.age;
ExpectAssignable<typeof v8Filter.age>()(42);
// @ts-expect-error Type '"taco"' is not assignable to type 'StrictCondition<ApplyBasicQueryCasting<number>> | undefined'.
const a1: AgeType = 'taco';
const TestModel = model('Test', new Schema({ age: Number, name: String }));
const query = TestModel.find({ age: { $gt: 18 } });
TestModel.find(query); // Should compile without errors
TestModel.findOne(query);
TestModel.deleteMany(query);
}
async function gh15786() {
interface IDoc {
nmae: string;
}
interface DocStatics {
m1(): void;
m2(): void;
}
const schema = new Schema<IDoc, Model<IDoc>, {}, {}, {}, DocStatics>({});
schema.static({ m1() {} });
}
async function gh15779_2() {
interface Job {
_id: Types.ObjectId;
name: string;
}
const jobSchema = new Schema<Job>({ name: String });
const JobModel = model<Job>('Job', jobSchema);
const jobs = await JobModel.aggregate<Job>([
{ $match: {} as QueryFilter<Job> }
]);
}
async function gh16062() {
const Test = model('Test', new Schema({ runtime: Number }));
// @ts-expect-error No overload matches this call.
await Test.findOne({ runtime: { $wrong: 100 } });
// @ts-expect-error No overload matches this call.
await Test.findOne({ $and: [{ runtime: { $wrong: 100 } }] });
}