Category Archives: MongoDB

MongoDB Server-Side JavaScript and Custom ID

Everybody loves ObjectId. It’s convenient, you never run out of numbers, and you feel yourself a hardcore programmer working with hex. You can even extract a timestamp out of it, which comes in handy quite often. After all, you can freely move data between collections and databases being sure every ID is unique.

However, some timid souls do not like it. I can’t take out of my head the picture of a customer trying to tell his 12-symbol-long receipt number by phone I recently witnessed, poor thing barely managed to provide it to the customer service. So, the task was clear – we need a simple transaction number that corresponds with following requirements:

  1. Consists of a predefined prefix followed by a number: AZ1854
  2. Numbers are consequent providing the prefix is the same
  3. We want it to be created as easily as possible, lazy programmers are good programmers (are they?)
  4. We continue using ObjectId for internal purposes as primary key (_id), which means the custom ID will be stored in another field.

To deal with all that we will create a MongoDB JavaScript function, save it into the database and call it whenever we need to create a new transaction. Sounds complicated? Of course it doesn’t!

Continue reading »