Skip to content

Using for _id with mongodb v4 library in TypeScript #58

@pjboardman

Description

@pjboardman

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());

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions