0

I am evaluating the following code to generate a short ID in my Node server (inspired by previous post: Short user-freiendly ID for mongo ):

> b = crypto.pseudoRandomBytes(6)
<SlowBuffer d3 9a 19 fe 08 e2>
> rid = b.readUInt32BE(0)*65536 + b.readUInt16BE(4)
232658814503138
> rid.toString(36).substr(0,8).toUpperCase()
'2AGXZF2Z'

This may not guarantee uniqueness, but my requirements are to have a short ID of maximum length 8 characters and it must also be all upper case. The purpose of this is to make the ID user friendly.

To ensure that there are no collisions, I am planning to create a collection in MongoDB that contains documents that map the short ID, which will be an indexed field, onto the MongoDB ObjectID of the actual document I want the short ID to refer to.

What is the best strategy for doing this to ensure scalability and performance in a concurrent environment where multiple process on multiple physical servers will be checking for short ID uniqueness?

Community
  • 1
  • 1
user3391835
  • 305
  • 1
  • 3
  • 14
  • Why not use `rid` as your document's `_id` property? That doesn't _have_ to be an `ObjectId`. MongoDB has a [unique index](http://docs.mongodb.org/manual/tutorial/create-a-unique-index/) on `_id` so you'll get an error when trying to insert a document with an `_id` that already exists (so you can generate a new id and re-insert it). – robertklep May 21 '15 at 20:04
  • I need to maintain the ObjectID for reasons that are outside the scope of the discussion here, but lets just assume that I can't change that. What would you suggest in that case? – user3391835 May 22 '15 at 08:35
  • I would probably add the `rid` as a property to the documents themselves (not through a "junction collection") and have a unique index on it to make sure you get an error when trying to insert a duplicate. – robertklep May 22 '15 at 08:37
  • Thanks - would this be suitable for a sharded mongoDB where multiple processes are inserting documents at the same time? – user3391835 May 22 '15 at 09:49
  • If you're using sharding (which isn't necessarily required to create a concurrent environment, so I didn't take it into consideration), see [this document](http://docs.mongodb.org/manual/tutorial/enforce-unique-keys-for-sharded-collections/). It may be difficult to ensure uniqueness across shards. – robertklep May 22 '15 at 09:55

0 Answers0