Skip to content

Commit ead5fa6

Browse files
authored
test(NODE-3468): Add tests for a strongly-typed Db (#2937)
This allows users who re-use a single db object to define which collections are available on that Db, as well as the types those collections contain. NODE-3468
1 parent fb0b27d commit ead5fa6

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

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

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { expectAssignable, expectNotType, expectType } from 'tsd';
2-
import { FindCursor, FindOptions, MongoClient, Document } from '../../../../src';
2+
import { FindCursor, FindOptions, MongoClient, Document, Collection, Db } from '../../../../src';
33
import type { Projection, ProjectionOperators } from '../../../../src';
44
import type { PropExists } from '../../utility_types';
55

@@ -9,7 +9,7 @@ const db = client.db('test');
99
const collection = db.collection('test.find');
1010

1111
// Locate all the entries using find
12-
collection.find({}).toArray((err, fields) => {
12+
collection.find({}).toArray((_err, fields) => {
1313
expectType<Document[] | undefined>(fields);
1414
});
1515

@@ -22,7 +22,7 @@ interface TestModel {
2222
}
2323

2424
const collectionT = db.collection<TestModel>('testCollection');
25-
await collectionT.find({
25+
collectionT.find({
2626
$and: [{ numberField: { $gt: 0 } }, { numberField: { $lt: 100 } }],
2727
readonlyFruitTags: { $all: ['apple', 'pear'] }
2828
});
@@ -74,7 +74,7 @@ const collectionBag = db.collection<Bag>('bag');
7474

7575
const cursor: FindCursor<Bag> = collectionBag.find({ color: 'black' });
7676

77-
cursor.toArray((err, bags) => {
77+
cursor.toArray((_err, bags) => {
7878
expectType<Bag[] | undefined>(bags);
7979
});
8080

@@ -198,3 +198,32 @@ expectType<FindOptions>(findOptions);
198198
// This is just to check that we still export these type symbols
199199
expectAssignable<Projection>({});
200200
expectAssignable<ProjectionOperators>({});
201+
202+
// Ensure users can create a custom Db type that only contains specific
203+
// collections (which are, in turn, strongly typed):
204+
type Person = {
205+
name: 'alice' | 'bob';
206+
age: number;
207+
};
208+
209+
type Thing = {
210+
location: 'shelf' | 'cupboard';
211+
};
212+
213+
interface TypedDb extends Db {
214+
collection(name: 'people'): Collection<Person>;
215+
collection(name: 'things'): Collection<Thing>;
216+
}
217+
218+
const typedDb = client.db('test2') as TypedDb;
219+
220+
const person = typedDb.collection('people').findOne({});
221+
expectType<Promise<Person | undefined>>(person);
222+
223+
typedDb.collection('people').findOne({}, function (_err, person) {
224+
expectType<Person | undefined>(person);
225+
});
226+
227+
typedDb.collection('things').findOne({}, function (_err, thing) {
228+
expectType<Thing | undefined>(thing);
229+
});

0 commit comments

Comments
 (0)