MongoDB with TypeScript


Uncategorized

Updated Aug 26th, 2022

When returning a document from mongoDB, create a type but you cannot use it without extending the default “WithId” type definition so for example:

CarDocType extends WithId

Be sure to “import type { WithId, Document } from ‘mongodb'” wherever the definition is taking place.

AND, what a headache figuring this out, your query needs to be wrapped in parenthesis with “as CarDocType” after the closing parenthesis:

const carDocument: CarDocType | null = (await client
.db()
.collection("cars")
.findOne({ _id: new ObjectId(carId) })) as CarDocType

When it comes to using storing the result from an await with TS, the type does not go on the variable but on the tail end with the “as” keyword. This is called typecasting in TypeScript.