-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
findX.test-d.ts
350 lines (296 loc) · 10.8 KB
/
findX.test-d.ts
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
import { expectAssignable, expectError, expectNotType, expectType } from 'tsd';
import type { Filter, Projection, ProjectionOperators } from '../../../../src';
import {
Collection,
Db,
Document,
FindCursor,
FindOptions,
MongoClient,
ObjectId,
WithId
} from '../../../../src';
import type { PropExists } from '../../utility_types';
// collection.findX tests
const client = new MongoClient('');
const db = client.db('test');
const collection = db.collection('test.find');
// Locate all the entries using find
collection.find({}).toArray((_err, fields) => {
expectType<WithId<Document>[] | undefined>(fields);
if (fields) {
expectType<ObjectId>(fields[0]._id);
expectNotType<ObjectId | undefined>(fields[0]._id);
}
});
// test with collection type
interface TestModel {
stringField: string;
numberField?: number;
fruitTags: string[];
readonlyFruitTags: readonly string[];
}
const collectionT = db.collection<TestModel>('testCollection');
collectionT.find({
$and: [{ numberField: { $gt: 0 } }, { numberField: { $lt: 100 } }],
readonlyFruitTags: { $all: ['apple', 'pear'] }
});
expectType<FindCursor<WithId<TestModel>>>(collectionT.find({}));
await collectionT.findOne(
{},
{
projection: {},
sort: {}
}
);
const optionsWithComplexProjection: FindOptions = {
projection: {
stringField: { $meta: 'textScore' },
fruitTags: { $min: 'fruitTags' },
max: { $max: ['$max', 0] }
},
sort: { stringField: -1, text: { $meta: 'textScore' }, notExistingField: -1 }
};
await collectionT.findOne({}, optionsWithComplexProjection);
// test with discriminated union type
interface DUModelEmpty {
type: 'empty';
}
interface DUModelString {
type: 'string';
value: string;
}
type DUModel = DUModelEmpty | DUModelString;
const collectionDU = db.collection<DUModel>('testDU');
const duValue = await collectionDU.findOne({});
if (duValue && duValue.type === 'string') {
// we can still narrow the result
// permitting fetching other keys that haven't been asserted in the if stmt
expectType<string>(duValue.value);
}
// collection.findX<T>() generic tests
interface Bag {
cost: number;
color: string;
}
const collectionBag = db.collection<Bag>('bag');
const cursor: FindCursor<WithId<Bag>> = collectionBag.find({ color: 'black' });
cursor.toArray((_err, bags) => {
expectType<WithId<Bag>[] | undefined>(bags);
});
cursor.forEach(
bag => {
expectType<WithId<Bag>>(bag);
},
() => {
return null;
}
);
expectType<WithId<Bag> | null>(
await collectionBag.findOne({ color: 'red' }, { projection: { cost: 1 } })
);
const overrideFind = await collectionBag.findOne<{ cost: number }>(
{ color: 'white' },
{ projection: { cost: 1 } }
);
expectType<PropExists<typeof overrideFind, 'color'>>(false);
// Overriding findOne, makes the return that exact type
expectType<{ cost: number } | null>(
await collectionBag.findOne<{ cost: number }>({ color: 'red' }, { projection: { cost: 1 } })
);
// NODE-3468 The generic in find and findOne no longer affect the filter type
type Pet = { type: string; age: number };
const pets = db.collection<Pet>('pets');
expectType<{ crazy: number }[]>(
await pets.find<{ crazy: number }>({ type: 'dog', age: 1 }).toArray()
);
interface Car {
make: string;
}
interface House {
windows: number;
}
const car = db.collection<Car>('car');
expectNotType<House | null>(await car.findOne({}));
interface Car {
make: string;
}
function printCar(car: Car | null) {
console.log(car ? `A car of ${car.make} make` : 'No car');
}
const options: FindOptions = {};
const optionsWithProjection: FindOptions = {
projection: {
make: 1
}
};
// this is changed in NODE-3454 to be the opposite test since Projection is flexible now
expectAssignable<FindOptions>({
projection: {
make: 'invalid'
}
});
printCar(await car.findOne({}, options));
printCar(await car.findOne({}, optionsWithProjection));
// Readonly tests -- NODE-3452
const colorCollection = client.db('test_db').collection<{ color: string }>('test_collection');
const colorsFreeze: ReadonlyArray<string> = Object.freeze(['blue', 'red']);
const colorsWritable: Array<string> = ['blue', 'red'];
// Permitted Readonly fields
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $in: colorsFreeze } })
);
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $in: colorsWritable } })
);
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $nin: colorsFreeze } })
);
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $nin: colorsWritable } })
);
// $all and $elemMatch works against single fields (it's just redundant)
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $all: colorsFreeze } })
);
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $all: colorsWritable } })
);
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $elemMatch: colorsFreeze } })
);
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $elemMatch: colorsWritable } })
);
const countCollection = client.db('test_db').collection<{ count: number }>('test_collection');
expectType<FindCursor<WithId<{ count: number }>>>(
countCollection.find({ count: { $bitsAnySet: Object.freeze([1, 0, 1]) } })
);
expectType<FindCursor<WithId<{ count: number }>>>(
countCollection.find({ count: { $bitsAnySet: [1, 0, 1] as number[] } })
);
const listsCollection = client.db('test_db').collection<{ lists: string[] }>('test_collection');
await listsCollection.updateOne({}, { list: { $pullAll: Object.freeze(['one', 'two']) } });
expectType<FindCursor<WithId<{ lists: string[] }>>>(listsCollection.find({ lists: { $size: 1 } }));
const rdOnlyListsCollection = client
.db('test_db')
.collection<{ lists: ReadonlyArray<string> }>('test_collection');
expectType<FindCursor<WithId<{ lists: ReadonlyArray<string> }>>>(
rdOnlyListsCollection.find({ lists: { $size: 1 } })
);
// Before NODE-3452's fix we would get this strange result that included the filter shape joined with the actual schema
expectNotType<FindCursor<{ color: string | { $in: ReadonlyArray<string> } }>>(
colorCollection.find({ color: { $in: colorsFreeze } })
);
// NODE-3454: Using the incorrect $in value doesn't mess with the resulting schema
expectNotType<FindCursor<{ color: { $in: number } }>>(
colorCollection.find({ color: { $in: 3 as any } }) // `as any` is to let us make this mistake and still show the result type isn't broken
);
expectType<FindCursor<WithId<{ color: string }>>>(
colorCollection.find({ color: { $in: 3 as any } })
);
// When you use the override, $in doesn't permit readonly
colorCollection.find<{ color: string }>({ color: { $in: colorsFreeze } });
colorCollection.find<{ color: string }>({ color: { $in: ['regularArray'] } });
// This is a regression test that we don't remove the unused generic in FindOptions
const findOptions: FindOptions<{ a: number }> = {};
expectType<FindOptions>(findOptions);
// This is just to check that we still export these type symbols
expectAssignable<Projection>({});
expectAssignable<ProjectionOperators>({});
// Ensure users can create a custom Db type that only contains specific
// collections (which are, in turn, strongly typed):
type Person = {
name: 'alice' | 'bob';
age: number;
};
type Thing = {
location: 'shelf' | 'cupboard';
};
interface TypedDb extends Db {
collection(name: 'people'): Collection<Person>;
collection(name: 'things'): Collection<Thing>;
}
const typedDb = client.db('test2') as TypedDb;
const person = typedDb.collection('people').findOne({});
expectType<Promise<WithId<Person> | null>>(person);
typedDb.collection('people').findOne({}, function (_err, person) {
expectType<WithId<Person> | null | undefined>(person); // null is if nothing is found, undefined is when there is an error defined
});
typedDb.collection('things').findOne({}, function (_err, thing) {
expectType<WithId<Thing> | null | undefined>(thing);
});
interface SchemaWithTypicalId {
_id: ObjectId;
name: string;
}
const schemaWithTypicalIdCol = db.collection<SchemaWithTypicalId>('a');
expectType<WithId<SchemaWithTypicalId> | null>(await schemaWithTypicalIdCol.findOne());
expectAssignable<SchemaWithTypicalId | null>(await schemaWithTypicalIdCol.findOne());
// should allow _id as an ObjectId
await schemaWithTypicalIdCol.findOne({ _id: new ObjectId() });
schemaWithTypicalIdCol.find({ _id: new ObjectId() });
interface SchemaWithOptionalTypicalId {
_id?: ObjectId;
name: string;
}
const schemaWithOptionalTypicalId = db.collection<SchemaWithOptionalTypicalId>('a');
expectType<WithId<SchemaWithOptionalTypicalId> | null>(await schemaWithOptionalTypicalId.findOne());
expectAssignable<SchemaWithOptionalTypicalId | null>(await schemaWithOptionalTypicalId.findOne());
// should allow _id as an ObjectId
await schemaWithTypicalIdCol.findOne({ _id: new ObjectId() });
await schemaWithTypicalIdCol.find({ _id: new ObjectId() });
interface SchemaWithUserDefinedId {
_id: number;
name: string;
}
const schemaWithUserDefinedId = db.collection<SchemaWithUserDefinedId>('a');
expectType<WithId<SchemaWithUserDefinedId> | null>(await schemaWithUserDefinedId.findOne());
const result = await schemaWithUserDefinedId.findOne();
if (result !== null) {
expectType<number>(result._id);
}
expectAssignable<SchemaWithUserDefinedId | null>(await schemaWithUserDefinedId.findOne());
// should allow _id as a number
await schemaWithUserDefinedId.findOne({ _id: 5 });
await schemaWithUserDefinedId.find({ _id: 5 });
// We should be able to use a doc of type T as a filter object when performing findX operations
interface Foo {
a: string;
}
const fooObj: Foo = {
a: 'john doe'
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const fooFilter: Filter<Foo> = fooObj;
// Specifically test that arrays can be included as a part of an object
// ensuring that a bug reported in https://jira.mongodb.org/browse/NODE-3856 is addressed
interface FooWithArray {
a: number[];
}
const fooObjWithArray: FooWithArray = {
a: [1, 2, 3, 4]
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const fooFilterWithArray: Filter<FooWithArray> = fooObjWithArray;
declare const coll: Collection<{ a: number; b: string }>;
expectType<WithId<{ a: number; b: string }> | null>((await coll.findOneAndDelete({ a: 3 })).value);
expectType<WithId<{ a: number; b: string }> | null>(
(await coll.findOneAndReplace({ a: 3 }, { a: 5, b: 'new string' })).value
);
expectType<WithId<{ a: number; b: string }> | null>(
(
await coll.findOneAndUpdate(
{ a: 3 },
{
$set: {
a: 5
}
}
)
).value
);
// projections do not change the return type - our typing doesn't support this
expectType<WithId<{ a: number; b: string }> | null>(
(await coll.findOneAndDelete({ a: 3 }, { projection: { _id: 0 } })).value
);