Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ObjectID (Mongodb) to String in JavaScript

I want to convert ObjectID (Mongodb) to String in JavaScript. When I get a Object form MongoDB. it like as a object has: timestamp, second, inc, machine. I can't convert to string.

like image 971
vhlen Avatar asked May 10 '13 08:05

vhlen


2 Answers

Try this:

objectId.str 

See the doc.

ObjectId() has the following attribute and methods:

[...]

  • str - Returns the hexadecimal string representation of the object.
like image 182
anubiskong Avatar answered Sep 23 '22 06:09

anubiskong


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.

like image 22
Sammaye Avatar answered Sep 25 '22 06:09

Sammaye