Crome developer tool show this
console.log('DATA*** ', data[0]._id);
error : DATA*** Object {_bsontype: "ObjectID", id: "YIä↵P¨H0"}
How I can convert it into normal JSON object?
Crome developer tool show this
console.log('DATA*** ', data[0]._id);
error : DATA*** Object {_bsontype: "ObjectID", id: "YIä↵P¨H0"}
How I can convert it into normal JSON object?
Share Improve this question edited Feb 12, 2020 at 9:57 Pushprajsinh Chudasama 7,9794 gold badges23 silver badges48 bronze badges asked May 17, 2017 at 13:06 Roman PawliwRoman Pawliw 571 gold badge3 silver badges7 bronze badges 1- Have you looked into bsondump? – evolutionxbox Commented May 17, 2017 at 13:08
3 Answers
Reset to default 2What you are looking for is JSON.stringify()
JSON.stringify(objectToSerialize)
You need to use JSON.stringify() and then JSON.parse() to convert bson to valid json.
const dataString = JSON.stringify(data[0]);
const parsed = JSON.parse(dataString);
console.log(parsed._id);
Other bson types may give you its associated representation in Canonical format. For example, if you used the decimal bsonType in your mongodb it will present it like so:
...(continuing from code block above)
console.log(parsed.aDecimalNumber); // { $numberDecimal: 1.00 }
you want to call the .tostring() function on the id field.
The objectId is held as a special type stored in hex to reduce size. You'll need to use the toString function to convert it to the 24 ascii char string
https://github./mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js#L171-L179
console.log('DATA*** ', data[0]._id.toString());