4

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?

2
  • Use 'bignumber.js' npm module to parse the integer value. use "var BigNumber = require('bignumber.js');x = new BigNumber(123.4567)" Commented Dec 4, 2015 at 12:12
  • 1
    What is the size of the integer the api requires as operation number? 32 bit? 64 bit? 128 bit? When it's 96 bit or more you could convert the hexadecimal representation of your ObjectId's to integers. Commented Dec 4, 2015 at 13:05

1 Answer 1

9

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.