Human readable/friendly IDs


#1

I’d like to give each ‘order’ (document) in an ‘orders’ collection a more human friendly unique identifier for use in an ecommerce app, where the customer would see their order ID and potentially need to reference in over the phone.

I think the default mongo IDs are just a little unwieldy for users (XZ62ARbFwqaYHFLtz), especially the use of mixed-case letters is quite difficult to say over the phone “upper case X, upper case Z, … lower case B etc”…

I’m thinking either 1. A auto-incremented numeric ID or 2. A more simple ID format - case insensitive and possibly a few characters shorter.

Has anyone implemented anything like this already? Any suggestions for how to approach it? I realise there are difficulties with both approaches. What about using the timestamp for when the document is created and hashing it? What problems might I run into?

Thanks!


#2

You can auto increment an id field, but make sure you call it server-side to make sure the ID is unique.

For example:

Meteor.methods({
    'addRecord':function(doc) {
        // Get the current latest id or if it's the first record use 1.
        currentId = MyCollection.findOne({},{sort:{id:-1}}).id || 1;
        doc.id = currentId + 1;
        FooCollection.insert(doc);
        return doc.id;
    }
});

#3

I read some comments on Stackoverflow that this solution is not guaranteed to work. Any other solutions available since the Mongo 3.2 upgrade of Meteor 1.4?


#4

One way is to let the “sleeping dogs lie”, so to say - don’t touch the defaults.

And, in parallel, create any fancy ID you want.

(For a demo project, I used this ‘strategy’, and my ids ran with “MINION#” glued to an auto-incrementing number.)