Reputation: 402
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?
Upvotes: 2
Views: 2649
Reputation: 8687
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));
}
Upvotes: 1
Reputation: 640
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;
};
Upvotes: 0
Reputation: 10780
ObjectIds do not accept seeds. If you just want custom _ids for your documents you can declare them as Strings, Numbers, etc in your schema.
Schema({ _id: String })
Upvotes: 1