How to generate random MongoDB ID in postman

I know we have {{$GUID}} to generate a random UUID v4, but do we have something similar for Object ID in postman?

Hey @kasir-barati :wave:

Welcome to the Postman Community! :postman:

Do you have an example of what that is?

You can use the scripting sandbox to create a random value that matches that using javascript and store that as a variable. That could be used in the request as a MongoDB Id.

I don’t actually know what the format of that id is though.


Not sure how useful that would be but this is what Postbot created for me:

function createObjectId() {
    const timestamp = Math.floor(Date.now() / 1000).toString(16); // 4 bytes (8 hex chars)
    const machineId = Math.random().toString(16).slice(2, 8).padEnd(6, '0'); // 3 bytes (6 hex chars)
    const processId = (Math.floor(Math.random() * 65536)).toString(16).padStart(4, '0'); // 2 bytes (4 hex chars)
    const counter = Math.floor(Math.random() * 16777216).toString(16).padStart(6, '0'); // 3 bytes (6 hex chars)

    return timestamp + machineId + processId + counter;
}

console.log(createObjectId()); // Example output: "65e93bff8a4d5c2b3e6f8bcd"