Can't use string ids with TypeScript

I’m trying to update my node.js driver for MongoDb from 4.13 to 5.x or 6.x. I’m using TypeScript.

For historical reasons, I’m using strings instead of BSON ObjectIDs for my document IDs. When I upgrade, I get this error:

error TS2322: Type 'string' is not assignable to type 'Condition<ObjectId>'.

136     await this.collection.updateOne({ _id: this.id }, [
                                          ~~~

If I cast the ID value to “any”, it compiles.

Is there a supported way to use string IDs with TypeScript without casting each ID?

Hey @Steve_Merel,

https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/write-operations/pkFactory/ may be what you’re looking for in this case.

1 Like

Hmm… I don’t think so. We already have a mechanism for generating string IDs.

This seems to be a problem with the TypeScript typings for the mongodb driver.

   await this.collection.updateOne({ _id: this.id }

worked before I upgraded.

After, I get a TypeScript error unless I cast all my IDs to any:

    await this.collection.updateOne({ _id: this.id as any}

I can certainly go through all my code and cast all IDs to any, but my understanding was that string IDs are supported by MongoDB. If that’s the case, shouldn’t the typings for the driver accept strings?

1 Like

+1

Seems like an easy fix to have _id be `string | ObjectID``