Class: ObjectID

ObjectID

Create a new ObjectID instance

Name Type Description
id string | number

Can be a 24 byte hex string, 12 byte binary string or a Number.

Properties:
Name Type Description
generationTime number

The generation time of this ObjectId instance

Returns:
of ObjectID.

Methods

staticObjectID.createFromHexString(hexString){ObjectID}

Creates an ObjectID from a hex string representation of an ObjectID.

Name Type Description
hexString string

create a ObjectID from a passed in 24 byte hexstring.

Returns:
the created ObjectID

staticObjectID.createFromTime(time){ObjectID}

Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.

Name Type Description
time number

an integer number representing a number of seconds.

Returns:
the created ObjectID

staticObjectID.isValid(){boolean}

Checks if a value is a valid bson ObjectId

Returns:
true if the value is a valid bson ObjectId, return false otherwise.

Compares the equality of this ObjectID with otherID.

Name Type Description
otherID object

ObjectID instance to compare against.

Returns:
result of comparing two ObjectID's
Example
// Compare two different ObjectID's using the equals method

var ObjectID = require('mongodb').ObjectID,
  test = require('assert');
// Create a new ObjectID
var objectId = new ObjectID();
// Create a new ObjectID Based on the first ObjectID
var objectId2 = new ObjectID(objectId.id);
// Create another ObjectID
var objectId3 = new ObjectID();
// objectId and objectId2 should be the same
test.ok(objectId.equals(objectId2));
// objectId and objectId2 should be different
test.ok(!objectId.equals(objectId3));

Generate a 12 byte id buffer used in ObjectID's

Name Type Description
time number optional

optional parameter allowing to pass in a second based timestamp.

Returns:
the 12 byte id buffer string.

Returns the generation date (accurate up to the second) that this ID was generated.

Returns:
generation date
Example
// Generate 12 byte binary string representation using a second based timestamp or
default value var ObjectID = require('mongodb').ObjectID, test = require('assert'); // Get a timestamp in seconds var timestamp = Math.floor(new Date().getTime()/1000); // Create a date with the timestamp var timestampDate = new Date(timestamp*1000); // Create a new ObjectID with a specific timestamp var objectId = new ObjectID(timestamp); // Get the timestamp and validate correctness test.equal(timestampDate.toString(), objectId.getTimestamp().toString());

Return the ObjectID id as a 24 byte hex string representation

Returns:
the 24 byte hex string representation.
Example
// Generate a 24 character hex string representation of the ObjectID

var ObjectID = require('mongodb').ObjectID,
  test = require('assert');
// Create a new ObjectID
var objectId = new ObjectID();
// Verify that the hex string is 24 characters long
test.equal(24, objectId.toHexString().length);