Convert ObjectID (Mongodb) to String in JavaScript

Try this:

objectId.str

See the doc.

ObjectId() has the following attribute and methods:

[...]

  • str - Returns the hexadecimal string representation of the object.

Here is a working example of converting the ObjectId in to a string

> a=db.dfgfdgdfg.findOne()
{ "_id" : ObjectId("518cbb1389da79d3a25453f9"), "d" : 1 }
> a['_id']
ObjectId("518cbb1389da79d3a25453f9")
> a['_id'].toString // This line shows you what the prototype does
function () {
    return "ObjectId(" + tojson(this.str) + ")";
}
> a['_id'].str // Access the property directly
518cbb1389da79d3a25453f9
> a['_id'].toString()
ObjectId("518cbb1389da79d3a25453f9") // Shows the object syntax in string form
> ""+a['_id'] 
518cbb1389da79d3a25453f9 // Gives the hex string

Did try various other functions like toHexString() with no success.


in the shell

ObjectId("507f191e810c19729de860ea").str

in js using the native driver for node

objectId.toHexString()