Node.js mongodb 无效的 _id 值

Node.js mongodb invalid _id values

一些公司代码一直在创建包含 _id 值的文档,这些值不是有效的 bson ObjectId 值。

这样做的代码如下所示:

var collection = getTheCollection();
collection.save(
    { _id: 'questionableId', /* more values */ },
    { w: 1, fsync: true },
    function(err, result) { /* ... */ }
)

当然,如果使用{ _id: new ObjectID('questionableId'), /* ... */ },会遇到以下错误:

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/.../mongodb-core/node_modules/bson/lib/bson/objectid.js:50:11)

幸运的是,一切似乎都运行良好,_id 属性中有很多值,例如 'questionableId'

这个代码可以接受吗?直觉上,我想为每个文档引入一个新的 id 属性,它可以愉快地存储像 'questionableId' 这样的值,并允许 mongo 本地处理生成 [=14] =] 属性.

我公司目前的代码有风险吗?

您无需担心当前的实施。不对 _id 字段使用 ObjectId 是一个有效的选择,这样做可能是有原因的(在考虑更改之前尝试了解背景)。

MongoDB documentation 状态:

MongoDB reserves the _id field in the top level of all documents as a primary key. _id must be unique, and always has an index with a unique constraint. However, except for the unique constraint you can use any value for the _id field in your collections.

请注意,切换到 ObjectId 后,您可能希望或不希望从某些隐含功能中获益。例如,您可以按照 here.

从其 ObjectId 中提取任何文档的创建数据

此外,ObjectId 可以说是迄今为止 _id 字段最常用的数据类型,我个人也建议使用它。