如何在Node.js中随机生成ObjectId

12

我需要在Node.js中随机生成ObjectId。是否有任何方法可以创建它?


“objectid”是什么意思?“Math.random()”是指什么? - MiniGod
像这样的24位ID是“5073c76a23ce3abf0f000001”。 - user1705980
1
我不知道这个12字节的“objectid”是什么,但你可以尝试从一个随机数的md5中取一个子字符串? - MiniGod
1
这是MongoDB生成ObjectId的方式:https://github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js - Ulysse BN
4个回答

44

如果您指的是 MongoDB 的 ObjectID,请尝试以下代码:

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

var objectId = new ObjectID();

9

生成mongoDB对象ID的另一种方式是:

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;
}

3

MongoDB中创建ObjectId:

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")

3

如果您使用TypeScript,您可以使用:

 import { Types } from 'mongoose';
  
 const _id  = new Types.ObjectId();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接