如何在node js中随机生成objectid

klsxnrf1  于 2023-03-17  发布在  Node.js
关注(0)|答案(4)|浏览(168)

我需要在node js中随机生成objectid,有没有办法创建。

pokxtpni

pokxtpni1#

如果您指的是MongoDB对象ID,请尝试以下操作:

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

var objectId = new ObjectID();
lqfhib0f

lqfhib0f2#

生成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;
}
flvlnr44

flvlnr443#

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

t2a7ltrp4#

如果要使用typeScript,可以用途:

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

相关问题