Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly generate objectid in node js

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

like image 840
user1705980 Avatar asked Oct 09 '12 09:10

user1705980


People also ask

How is ObjectId generated?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes.

How do I get a unique ID in node?

Using the uuid Package Unlike the crypto module, the uuid package is a third-party npm module. To install it, run the following command. uuid allows you to generate different ID versions: Version 1 and 4 generate a unique ID randomly generated.

Does Mongoose automatically create ID?

Ids. By default, Mongoose adds an _id property to your schemas. const schema = new Schema(); schema.path('_id'); // ObjectId { ... } When you create a new document with the automatically added _id property, Mongoose creates a new _id of type ObjectId to your document.

How is MongoDB's _ID generated?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record.


3 Answers

If you mean a MongoDB ObjectID, try this:

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

var objectId = new ObjectID();
like image 131
Werner Kvalem Vesterås Avatar answered Oct 18 '22 13:10

Werner Kvalem Vesterås


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;
}
like image 31
C M Avatar answered Oct 18 '22 13:10

C M


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")
like image 42
SridharKritha Avatar answered Oct 18 '22 13:10

SridharKritha