我有一組由于用戶互動而被添加的檔案。這些檔案已經有一個_id欄位,但我還想為每個現有和新創建的物件添加一個唯一的人類可讀 ID,其形式為D123456
添加此類 ID 并確保所有這些 ID 都是唯一的最佳方法是什么?
uj5u.com熱心網友回復:
MongoDB 沒有像關系資料庫那樣的自動增量選項。
您可以自己實作一些東西:在保存檔案之前,生成一個 ID。首先,創建一個資料庫集合,其唯一目的是保存一個計數器:
const Counter = mongoose.model('Counter', new mongoose.schema({
current: Number
}));
其次,在保存物件之前,查找并增加集合中的數字:
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 個字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/423994.html
上一篇:如何在將uniqueID存盤為字串且uniqueID來自另一個集合而不是objectID的檔案中填充陣列
下一篇:如何在貓鼬模式中回圈專案
