Search code examples
javascriptjsonnode.jsbson

_bson ObjectId convert into JSON object?


I tried convert it into JSON. _id: Object _bsontype: "ObjectID" id: "X±¸kÍ+I¿9À"

How to convert into JSON format?


Solution

  • From https://github.com/mongodb/js-bson

    you need to call deserialize from BSON

    var doc_2 = bson.deserialize(data);
    JSON.stringify(doc_2);
    

    reading that function https://github.com/mongodb/js-bson/blob/1.0-branch/extended-json/index.js#L48

    you can expect your output to maintain the "type" for you...

    {_id:{"$oid":"58b1bf5bcba40a6a5671620c"}}
    

    If you really just want the string for the OID, you can simply overwrite the string back into the _id key

    doc["_id"] = doc["_id"].toString()
    JSON.stringify(doc);