Monday, 24 April 2017

Is it recommended to use custom ObjectID with Mongodb?

First read my code

import { ObjectID } from 'mongodb';
import * as keygen from 'uid-generator';

// random friendly ObjectID generator
const MyObjectID = (id? : string) ObjectID => {
    const uid = new keygen(null, keygen.BASE58, 12);
    let objectId = id ?  new Buffer(id, 'ascii') : new Buffer(uid.generateSync(), 'ascii');
    return ObjectID(objectId.toString('hex')); // return MongoDB ObjectId
}

I'm basically generating a base58 12 bytes random string with this library (uid-generator)

And then convert it to hexdecimal then use the hexdecimal with MongoDB ObjectID

it looks like this

let oid = MyObjectID();
> ObjectId("7556685542544555317a7843") // string : 'uVhUBTEU1zxC'
db.mycollection.insert({ _id : oid, fieldX : "valueX" });
> { ok : 1 }

when I want to query data

oid = MyObjectID('uVhUBTEU1zxC')
db.mycollection.find({ _id : ObjectID(oid) });
> { _id : ObjectId("7556685542544555317a7843"), "fieldX" : "valueX" }

oid
ObjectId("7556685542544555317a7843")

oid.str
> '7556685542544555317a7843'

oid.getTimestamp()
> ISODate("2032-05-19T16:31:17Z") // it even gives a valid date, don't care about it much, it is not relevant for me to get the right exact timestamp from the ObjectID

Is this proper way to do it ? does this insure uniqueness on the system ?



via user7887107

No comments:

Post a Comment