如何生成唯一的 6 位数字以用作集合中文档的 ID?

How to generate a unique 6 digits number to use as an ID for documents in a collection?

我有一组文档,这些文档是由于用户交互而添加的。 这些文档已经有一个 _id 字段,但我还想以 D123456

的形式为每个现有的和新创建的对象添加一个唯一的人类可读 ID

添加此类 ID 并确保所有这些 ID 都是唯一的最佳方法是什么?

MongoDB 没有像关系数据库那样的 auto-increment 选项。

您可以自己实施一些操作:在保存文档之前,生成一个 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-specific,但这应该可以工作)

格式由您决定。如果您有超过 999999 个文档,示例中的 'nice looking ID' 将变得更长并且超过 7 个字符。