uniku
Reference

ObjectID

MongoDB-compatible 12-byte identifiers.

ObjectID matches MongoDB's native 12-byte representation. Use it when your application stores _id values alongside MongoDB clients or needs to preserve that wire format.

import { objectid } from 'uniku/objectid'

const documentId = objectid()
// '6a53c3139f0aac9835059f6f' (string)

Generated API reference

Public methods

Read source

Generate a MongoDB ObjectID string or write the bytes into a buffer. ObjectID is a 12-byte identifier consisting of a 4-byte timestamp, a 5-byte per-process random value, and a 3-byte always-incrementing counter, encoded as a 24-character lowercase hex string. It is time-ordered and compatible with MongoDB's own ObjectID implementation.

objectid

Generate a MongoDB-compatible ObjectID string.

objectid(): string

Generate an ObjectID with explicit options or write its 12 canonical bytes into a caller-owned buffer.

objectid<TBuf extends Uint8Array = Uint8Array>(options: ObjectIdOptions | undefined, buf: TBuf, offset?: number): TBuf

Generate an ObjectID string with optional timestamp, random field, or counter.

objectid(options?: ObjectIdOptions, buf?: undefined, offset?: number): string

ObjectIdOptions

random?

5 bytes of random data to use for the ObjectID's random field.

Uint8Array
secs?

Timestamp in seconds since Unix epoch. Defaults to Math.floor(Date.now() / 1000).

number
counter?

24-bit counter value (0 to 0xFFFFFF).

number
Exampleobjectid()// => '6a53c3139f0aac9835059f6f'
toBytes

Convert an ObjectID string to its canonical 12-byte representation.

toBytes(id: string): Uint8Array
Exampleobjectid.toBytes('6a53c3139f0aac9835059f6f')// => Uint8Array [106, 83, 195, 19, 159, 10, 172, 152, 53, 5, 159, 111]
fromBytes

Convert 12 canonical ObjectID bytes to an ObjectID string.

fromBytes(bytes: Uint8Array): string
Exampleobjectid.fromBytes(Uint8Array.from([106, 83, 195, 19, 159, 10, 172, 152, 53, 5, 159, 111]))// => '6a53c3139f0aac9835059f6f'
timestamp

Read the embedded Unix timestamp in milliseconds.

timestamp(id: string): number
Exampleobjectid.timestamp('6a53c3139f0aac9835059f6f')// => 1783874323000
isValid

Return whether a value is a syntactically valid ObjectID string.

isValid(id: unknown): id is string
Exampleobjectid.isValid('6a53c3139f0aac9835059f6f')// => true
NIL

The nil ObjectID (all zeros)

NIL: string
Exampleobjectid.NIL// => '000000000000000000000000'
MAX

The max ObjectID (all 0xff)

MAX: string
Exampleobjectid.MAX// => 'ffffffffffffffffffffffff'