MongoDB with TypeScript


Updated Jun 6th, 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 defintion 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
.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 as