'Create ObjectId in mongoose using a seed string
I want to create an objectid in mongoose using a seed string eg-
Id = new ObjectId("alex");
Something on similar lines. But whatever examples I saw to generate the objectid require you to pass in the string in the objectid's hash format.
Is there a way to do what i want?
Solution 1:[1]
If anyone is still looking for a solution, the following gist may help.
import mongoose from "mongoose";
import RandomGenerator from "random-seed-generator";
const mockIt = (modifier = Math.random()) => {
let mock = RandomGenerator.createWithSeeds("Mock" + modifier).hexString(24);
return mock;
};
export const mockObjectId = (str, options) => {
const { plainText = false } = options || {};
const id = mongoose.Types.ObjectId(mockIt(str));
return plainText ? id.toString() : id;
};
Solution 2:[2]
You can use this code
/**
* https://docs.mongodb.com/manual/reference/method/ObjectId/
* @param seed - string allowing to create predictable mongo id value ( the same for any execution )
* @param date - date of creation - first 4 bytes of id
* @returns {ObjectId}
*/
function mongoIdFromSeed(seed, date = "2022-01-01") {
return new ObjectID(dayjs(date).unix().toString(16) + crypto.createHash("md5").update(seed).digest("hex").substr(0, 16));
}
for given seed and date you will obtain the same results any time.
This code depends on library dayjs you can remove this dependency using
new Date(date).getTime() / 1000 | 0
to instead of unix method. I mean
function mongoIdFromSeed(seed, date = "2022-01-01") {
return new ObjectID((new Date(date).getTime() / 1000 | 0).toString(16) + crypto.createHash("md5").update(seed).digest("hex").substr(0, 16));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ric0 |
| Solution 2 | Daniel |
