Docs HomeNode.js

Generate Custom Values for _id_id生成自定义值

Overview概述

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.在本指南中,您可以学习如何使用MongoDB Node.js驱动程序使用主键工厂生成自己的_id值。

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. 主键工厂允许您在插入操作期间选择不指定_id时在文档中创建唯一标识符。The default primary key factory generates ObjectId values.默认主键工厂生成ObjectId值。

Note

Upsert OperationsUpsert操作

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. 驱动程序不使用主键工厂进行upsert操作,因为它无法确定是否应用主键工厂。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.如果在追加启动操作中指定了主键工厂,并且它执行插入操作,则服务器会自动生成该文档的ObjectId

If you want to use your specified primary key factory, perform a find operation, then an update or insert operation.如果要使用指定的主键工厂,请执行查找操作,然后执行更新插入操作。

Specify a Primary Key Factory指定主键工厂

To specify a primary key factory, apply the pkFactory option to your MongoClient instance.要指定主键工厂,请将pkFactory选项应用于MongoClient实例。

The following code snippet applies the pkFactory option to generate _id values of type uuid:以下代码片段应用pkFactory选项生成uuid类型的_id值:

const { UUID } = require('bson');
...
const client = new MongoClient(uri, {
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.如果插入的文档的_id字段的类型与主键工厂指定的类型不同,则数据将不一致。

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:例如,如果在生成uuid类型的主键工厂上运行以下插入操作,则_id值将同时包含uuidstring类型:

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

Additional Information附加信息

To learn more about the types, interfaces, and classes discussed in this section, see the following resources:要了解本节中讨论的类型、接口和类的更多信息,请参阅以下资源: