How to randomly generate objectid in node js
Asked Answered
I

4

13

I need to randomly generate objectid in node js.Is there is any way to create.

Instill answered 9/10, 2012 at 9:40 Comment(4)
What do you mean by objectid? Math.random()?Inferno
24 digit id "5073c76a23ce3abf0f000001" like this.Instill
I have no idea what this 12byte objectid is, but you can try to take a substring of a md5 of a random number?Inferno
Here is how MongoDB generate objectids: github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.jsGlyptics
L
44

If you mean a MongoDB ObjectID, try this:

var ObjectID = require('mongodb').ObjectID;

var objectId = new ObjectID();
Lemaster answered 9/10, 2012 at 11:45 Comment(0)
B
9

Another way to generate the mongoDB object id is.

function objectId() {
    const os = require('os');
    const crypto = require('crypto');

    const secondInHex = Math.floor(new Date()/1000).toString(16);
    const machineId = crypto.createHash('md5').update(os.hostname()).digest('hex').slice(0, 6);
    const processId = process.pid.toString(16).slice(0, 4).padStart(4, '0');
    const counter = process.hrtime()[1].toString(16).slice(0, 6).padStart(6, '0');

    return secondInHex + machineId + processId + counter;
}
Bentham answered 8/11, 2019 at 8:7 Comment(0)
A
3

Creating ObjectId in the mongodb:

const {ObjectId} = require('mongodb'); 

// Method 1:
const myId = new ObjectId(); // No argument
// say, myId = ObjectId("507f1f77bcf86cd799439011")

// Access the Hexadecimal String from the ObjectId
console.log(ObjectId("507f1f77bcf86cd799439011").str); 
// 507f1f77bcf86cd799439011

// Method 2: Specify your own unique Hexadecimal String (12 bytes long)
const myId = new ObjectId("507f191e810c19729de860ea"); // with argument
// myId = ObjectId("507f191e810c19729de860ea")
Atony answered 23/11, 2021 at 12:39 Comment(0)
P
3

If you would use typeScript you can use :

 import { Types } from 'mongoose';
  
 const _id  = new Types.ObjectId();
Prosenchyma answered 15/3, 2023 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.