Skip to content

Instantly share code, notes, and snippets.

@dchest
Created February 5, 2016 20:38
Show Gist options
  • Save dchest/4dc5d2299e059d22f5bc to your computer and use it in GitHub Desktop.
Save dchest/4dc5d2299e059d22f5bc to your computer and use it in GitHub Desktop.
MongoDB/BSON ObjectId generator in Node.js
var os = require('os');
var crypto = require('crypto');
var machineId = crypto.createHash('md5').update(os.hostname()).digest().slice(0, 3);
var objectIdCounter = crypto.randomBytes(4).readUInt32BE() & 0xffffff;
// Returns a unique objectId as a hex string.
function newObjectId() {
var buf = new Buffer(12);
// Current time, 4 bytes.
buf.writeUInt32BE(Math.floor(Date.now() / 1000), 0);
// Machine ID, 3 bytes.
machineId.copy(buf, 4);
// Process ID, 2 bytes.
buf.writeUInt16BE(process.pid, 7);
// Global counter, 3 bytes.
buf.writeUInt8((objectIdCounter >>> 16) & 0xff, 9);
buf.writeUInt8((objectIdCounter >>> 8) & 0xff, 10);
buf.writeUInt8((objectIdCounter >>> 0) & 0xff, 11);
objectIdCounter = (objectIdCounter + 1) & 0xffffff;
return buf.toString('hex');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment