Generate Custom Values for _id
为_id
生成自定义值
_id
On this page本页内容
Overview概述
In this guide, you can learn how to use the MongoDB Node.js driver to generate your own 在本指南中,您可以学习如何使用MongoDB Node.js驱动程序使用主键工厂生成自己的_id
values using the primary key factory._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
值。
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() }
});
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
值将同时包含uuid
和string
类型:
myColl.insertOne({ _id: "user1388", ... });
Additional Information附加信息
To learn more about the types, interfaces, and classes discussed in this section, see the following resources:要了解本节中讨论的类型、接口和类的更多信息,请参阅以下资源: