I’m using the ~latest MongoDB (v6.6.2) in a TypeScript environment.
I have this function:
export async function getCollection<T extends Document>(collection_name: string, skip: number, limit: number, filter: Filter<Document>): Promise<T[]> {
try {
let database = await connectToDatabase();
return database.collection<T>(collection_name).find(filter).skip(skip).limit(limit).toArray();
} catch (error) {
console.error(error);
throw error;
}
}
which I invoke like so:
const deviceDBs = await getCollection<DeviceDB>("devices", 0, 0, { location_id: ObjectId.createFromHexString(locationId) });
This code works, but lacks significant typesafety on its filter. I want to generate a TypeScript error if I provide an invalid filter property. location_id
is part of the DeviceDB
type, but this code continues to compile if I change location_id
to foo
which is not desirable.
I tried to make this work by changing to filter: Filter<Partial<T>>
but that fails to satisfy the type definition for find
because it expects to be given T
:
find(): FindCursor<WithId<TSchema>>;
find(filter: Filter<TSchema>, options?: FindOptions): FindCursor<WithId<TSchema>>;
find<T extends Document>(filter: Filter<TSchema>, options?: FindOptions): FindCursor<T>;
I found this existing StackOverflow post but it implies things should “just work” when that is not my experience.
2