Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Generate Custom Values for _id

On this page

  • Overview
  • Specify a Primary Key Factory
  • Additional Information

In this guide, you can learn how to use the MongoDB Node.js driver to generate your own _id values using the primary key factory.

The primary key factory allows you to create unique identifiers in your documents when you choose not to specify an _id during an insert operation. The default primary key factory generates ObjectId values.

Note

Upsert Operations

The driver doesn't use the primary key factory for upsert operations because it's unable to determine whether to apply the primary key factory. If you specified the primary key factory in an upsert operation and it performs an insert operation, the server autogenerates an ObjectId for that document.

If you want to use your specified primary key factory, perform a find operation, then an update or insert operation.

To specify a primary key factory, apply the pkFactory option to your MongoClient instance.

The following code snippet applies the pkFactory option to generate _id values of type uuid:

const { UUID } = require('bson');
...
const client = new MongoClient(uri, {
useUnifiedTopology: true,
pkFactory: { createPk: () => new UUID().toBinary() }
});

Note

Data Consistency

If you insert a document with an _id field with a different type than the type specified by the primary key factory, then you will have inconsistent data.

For example, if you run the following insert operation on a primary key factory that generates uuid types, your _id values will contain both the uuid and string types:

collection.insertOne({ _id: "user1388", ... });

To learn more about the types, interfaces, and classes discussed in this section, see the following resources:

←  Insert a DocumentDelete a Document →