cdimascio / uuid-mongodb

📇 Generates and parses MongoDB BSON UUIDs
MIT License
101 stars 17 forks source link

Using for _id with mongodb v4 library in TypeScript #58

Open pjboardman opened 3 years ago

pjboardman commented 3 years ago

In case someone else runs into this...I was using uuid-mongodb successfully with v3 of the mongodb library, using a UUID as the document _id. Had to upgrade to mongodb v4 and things broke.

Finally found the clue here: https://jira.mongodb.org/browse/NODE-3532?focusedCommentId=3989765&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-3989765

Here's some sample code, if you don't want to register. The key is using an interface ("IdDocument" below) as the generic when accessing client.db.collection.

Need an interface:

import { MUUID } from 'uuid-mongodb';

export interface IdDocument {
  _id: MUUID;
  [keys: string]: any;
}

and then:

import { v4, from, MUUID } from 'uuid-mongodb';

const id = v4();
const data = { _id: id,  someValue: 'heres a thing' };

const coll = client.db('test').collection<IdDocument>('testids');

await coll.insertOne(data);
const output = await coll.findOne({_id: id }) as IdDocument;

console.log(id.toString(), from(output?._id).toString());
ghost commented 3 years ago

Good find, but something is definately still wrong. This would essentially make the document a typeless object - antipattern to Typescript and pointless .collection<T> generic in the first place.

Can you also just make your interface as normal and extends IdDocument to get it working as well?

pjboardman commented 3 years ago

100%. This simple example was just to isolate the illustration of the _id handling. You would most definitely want to extend IdDocument in your codebase (and drop the [keys: string]: any; property). To go the extra mile, you'd probably also want to: _id: Binary so that you don't tie your domain directly to uuid-mongodb (you would need some additional code to make that work).

There are probably other things, this was just to indicate a general (not specific) direction for how to address the upgrade of mongodb 3.x to mongodb 4.x while still using uuid-mongodb.