Mongo DB ObjectId
From Logic Wiki
_id is 12 bytes and
- first 4 bytes are timestamp
- next 3 bytes Machine identifier
- next 2 bytes process identifier
- last 3 bytes counter
if only we record more than 16 million records on the same machine same processor and same second then id will not be unique
id is generated by driver not by MongoDB
Contents
Generating id manually
const mongoose = require('mongoose');
const id = new mongoose.Types.ObjectId();
console.log(id);
extract timestamp from id
console.log(id.getTimestamp());
Checking validation of the Object Id
const isValid = mongoose.Types.ObjectId.isValid('1234');
console.log(idValid);
joi-objectid
To validate ObjectIDs using joi, use joi-objectid NPM package.