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

Time:02-15

I have a collection of documents which are being added as a result of users' interactions. Those docs already have an _id field, but I also wanna add a unique human readable ID for every existing and newly created object, in a form of D123456

What is the best way of adding such an ID and being sure that all those IDs are unique?

CodePudding user response:

MongoDB doesn't have an auto-increment option like relational databases.

You can implement something yourself: before you save your document, generate an ID. First, create a database collection whose sole purpose is to hold a counter:

const Counter = mongoose.model('Counter', new mongoose.schema({
  current: Number
}));

Second, before you save your object, find and increment the number in the collection:

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');
}

Note: I've tested the query in MongoDB (except for the 'returnDocument' option, which is Mongoose-specific, but this should work)

Formatting is up to you. If you have more than 999999 documents, the 'nice looking ID' in the example will just get longer and be 7 characters.

  • Related