【发布时间】:2022-02-14 21:50:08
【问题描述】:
我有一组由于用户交互而被添加的文档。
这些文档已经有一个 _id 字段,但我还想为每个现有和新创建的对象添加一个唯一的人类可读 ID,其形式为 D123456
添加此类 ID 并确保所有这些 ID 都是唯一的最佳方法是什么?
【问题讨论】:
我有一组由于用户交互而被添加的文档。
这些文档已经有一个 _id 字段,但我还想为每个现有和新创建的对象添加一个唯一的人类可读 ID,其形式为 D123456
添加此类 ID 并确保所有这些 ID 都是唯一的最佳方法是什么?
【问题讨论】:
MongoDB 没有像关系数据库那样的自动增量选项。
您可以自己实现一些东西:在保存文档之前,生成一个 ID。首先,创建一个数据库集合,其唯一目的是保存一个计数器:
const Counter = mongoose.model('Counter', new mongoose.schema({
current: Number
}));
其次,在保存对象之前,find and increment 集合中的数字:
const humanReadableDocumentId = await Counter.findOneAndUpdate(
// If you give this record a name, you can have multiple counters.
{ _id: 'humanReadableDocumentId' },
{ $inc: { current: 1 } },
// If no record exists, create one. Return the new value after updating.
{ upsert: true, returnDocument: 'after' }
);
const yourDocument.set('prettyId', format(humanReadableDocumentId.current));
function format(id) {
// Just an example.
return 'D' + id.toString().padStart(6, '0');
}
注意:我已经在 MongoDB 中测试了查询(除了 'returnDocument' 选项,它是 Mongoose 特有的,但这应该可以工作)
格式由您决定。如果您有超过 999999 个文档,则示例中的“好看的 ID”会变得更长,超过 7 个字符。
【讨论】: