How Serialize Mongodb Objectid("uniqueid") To Json In Nodejs?
Let's assume we have a query builder service B that spits out mongo db query when called. This query is received by service A and it executes it as is with mongo db official nodejs
Solution 1:
You need to:
- Serialize your documents to extended json on one end
- Deserialize your documents from extended json to language-native data structures on the other end
See https://github.com/mongodb/js-bson#node-no-bundling for how to serialize and deserialize.
You cannot feed extended json-type annotated hashes to driver functions that expect native types (which are all of them, basically, other than the one that specifically parses extended json), like you tried to do.
var q = { _id: new mongo.ObjectID("5f3258cfbaaccedaa5dd2d96") };
const serializedQ = BSON.serialize(q);
const deserializedQ = BSON.deserialize(serializedQ);
const result = awaitthis.db.collection("persons").find(deserializedQ).toArray();
Solution 2:
There is a standard that MongoDB calls "Extended JSON" that defines how you can encode all BSON data types in regular JSON.
It will become something like
{ _id : {$oid: "5f3258cfbaaccedaa5dd2d96"} }
Most MongoDB tools will be able to convert to and from that format.
Post a Comment for "How Serialize Mongodb Objectid("uniqueid") To Json In Nodejs?"