Roman Pawliw
Roman Pawliw

Reputation: 57

_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?

Upvotes: 0

Views: 4249

Answers (1)

bauman.space
bauman.space

Reputation: 2023

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);

Upvotes: 1

Related Questions