Nodari L
Nodari L

Reputation: 1178

Get unique int from MongoDB ObjectId in JavaScript(NodeJS)?

I'm involved in a project where we use MongoDB as the primary database system and JavaScript/NodeJS for the server side. We need to make an integration with external partner.

Our partner's API requires operation number which should be a unique integer value. We decided to use a combination of 4 byte timestamp and 3 byte random increment value from ObjectId, but the result numbers are too high and we lose precision.

Here is the procedure

var getUniqueIntFromObjectId = function (object_id) {
    var res = null;
    object_id = object_id.toString();
    res = parseInt(object_id.substring(0, 8), 16).toString() + parseInt(object_id.substring(18, 24), 16).toString();
    return parseInt(res, 10);
};

How can we improve this procedure, or change it to achieve the goal?

Upvotes: 4

Views: 3411

Answers (1)

Alex
Alex

Reputation: 21766

You can get a valid integer by picking an initial ObjectId (oldest one in your table) and use this to offset the timestamp in the first 4 bytes. This will give you a smaller number that is a valid integer without losing uniqueness. Alternatively you could set your initial ObjectId to 500000000000000000000000 which corresponds to 2012-07-13T11:01:20.000Z

var getUniqueIntFromObjectId = function (object_id) {
    var res = null;
    object_id = object_id.toString();
    var firstObjectId='5661728913124370191fa3f8'
    var delta = parseInt(object_id.substring(0, 8), 16)-parseInt(firstObjectId.substring(0, 8),16)
    res = delta.toString() + parseInt(object_id.substring(18, 24), 16).toString();
    return parseInt(res, 10);
};

document.write("Unique integer: <br>" + getUniqueIntFromObjectId("56618f7d0000000000000000"))
document.write('<br/>')
document.write("Max safe integer: <br>"+Number.MAX_SAFE_INTEGER)

Upvotes: 9

Related Questions