[英]Node.js mongodb invalid _id values
Some company code has been creating documents with _id
values that are not valid bson ObjectId
values. 某些公司代码已使用
_id
值(不是有效的bson ObjectId
值)创建文档。
The code that has done so looks like: 这样做的代码如下:
var collection = getTheCollection();
collection.save(
{ _id: 'questionableId', /* more values */ },
{ w: 1, fsync: true },
function(err, result) { /* ... */ }
)
Of course, if { _id: new ObjectID('questionableId'), /* ... */ }
, was used the following error would be encountered: 当然,如果使用
{ _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)
Fortunately, everything seems to be working fine, with plenty of values like 'questionableId'
in _id
properties. 幸运的是,一切似乎都运行良好,在
_id
属性中有很多值,例如'questionableId'
。
Is this code acceptable? 此代码可以接受吗? Intuitively, I'd like to introduce a new
id
property for every document which can happily store values like 'questionableId'
, and allow mongo to natively handle generating an _id
property. 直观地讲,我想为每个文档引入一个新的
id
属性,该属性可以愉快地存储'questionableId'
等值,并允许mongo本地处理生成_id
属性。
Is my company's current code risky? 我公司当前的代码有风险吗?
You don't need to worry about the current implementation. 您无需担心当前的实现。 It's a valid choice not to use an
ObjectId
for the _id
field and there may have been reasons why things were done this way (try to find out about the background before you consider changing things). 不对
_id
字段使用ObjectId
是一个有效的选择,并且可能由于某些原因使用了这种方式(尝试在考虑更改之前先了解背景)。
The MongoDB documentation states: MongoDB文档指出:
MongoDB reserves the _id field in the top level of all documents as a primary key.
MongoDB在所有文档的顶层保留_id字段作为主键。 _id must be unique, and always has an index with a unique constraint.
_id必须是唯一的,并且始终具有带有唯一约束的索引。 However, except for the unique constraint you can use any value for the _id field in your collections.
但是,除了唯一约束之外,您可以为集合中的_id字段使用任何值。
Mind you, there are certain implicit features that you may or may not want to benefit from by switching to an ObjectId
. 请注意,某些隐式功能可能会或可能不会希望通过切换到
ObjectId
而受益。 You can, for instance, extract the creation data of any document from its ObjectId
as described here . 例如,您可以按此处所述从其
ObjectId
提取任何文档的创建数据。
Also, ObjectId
is arguably by far the most used data type for the _id
field and I would personally recommend using it, too. 同样,
ObjectId
可以说是_id
字段中最常用的数据类型,我个人也建议使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.