Convert ObjectID (Mongodb) to String in JavaScript

后端 未结 16 1299
青春惊慌失措
青春惊慌失措 2020-12-02 19:50

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

16条回答
  •  Happy的楠姐
    2020-12-02 20:22

    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.

提交回复
热议问题