Is there any way to create mongodb like _id strings without mongodb?
Solution 1
Object IDs are usually generated by the client, so any MongoDB driver would have code to generate them.
If you're looking for JavaScript, here's some code from the MongoDB Node.js driver:
https://github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js
And another, simpler solution:
https://github.com/justaprogrammer/ObjectId.js
Solution 2
A very easy pseudo ObjectId generator in javascript:
const ObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) =>
s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h))
Solution 3
I have a browser client that generates ObjectId
s. I wanted to make sure that I employ the same ObjectId
algorithm in the client as the one used in the server. MongoDB has js-bson which can be used to accomplish that.
If you are using javascript with node.
npm install --save bson
Using require statement
var ObjectID = require('bson').ObjectID;
var id = new ObjectID();
console.log(id.toString());
Using ES6 import statement
import { ObjectID } from 'bson';
const id = new ObjectID();
console.log(id.toString());
The library also lets you import using good old script tags but I have not tried this.
Solution 4
Extending Rubin Stolk's and ChrisV's answer in a more readable syntax (KISS).
function objectId () {
return hex(Date.now() / 1000) +
' '.repeat(16).replace(/./g, () => hex(Math.random() * 16))
}
function hex (value) {
return Math.floor(value).toString(16)
}
export default objectId
Solution 5
ruben-stolk's answer is great, but deliberately opaque? Very slightly easier to pick apart is:
const ObjectId = (rnd = r16 => Math.floor(r16).toString(16)) =>
rnd(Date.now()/1000) + ' '.repeat(16).replace(/./g, () => rnd(Math.random()*16));
(actually in slightly fewer characters). Kudos though!
fancy
Updated on August 07, 2021Comments
-
fancy almost 3 years
I really like the format of the _ids generated by mongodb. Mostly because I can pull data like the date out of them client side. I'm planning to use another database but still want that type of _id for my document. How can I create these ids without using mongodb?
Thanks!
-
webjay almost 8 yearsand
mongoose.Types.ObjectId.isValid
saytrue
-
honkskillet about 6 yearsI used id.toHexString() to get the string.
-
Grant Carthew almost 6 yearsLooks like the js file has been moved: github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js
-
Robert over 4 yearsThis should be the right answer... use the same code MongoDB does folks! I'm using bson 4.0.2 and it's working just fine for me. Note that the name is "ObjectId" (lowercase D)
-
Tamas over 2 yearsif you already have
mongoose.Types
, then you can also callnew mongoose.Types.ObjectId()