SamuraiJack
SamuraiJack

Reputation: 5539

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 driver.

How do I send something like :

[{
  _id: new mongo.ObjectID("5f3258cfbaaccedaa5dd2d96"),
  phone: "666"
}, {
  _id: new mongo.ObjectID("5f3258cfbaaccedaa5dd2da2"),
  phone: "555"
}]

from service B to service A?

EDIT:

The following works perfectly fine:

var q = { _id: new mongo.ObjectID("5f3258cfbaaccedaa5dd2d96") };
const result = await this.db.collection("persons").find(q).toArray();

The following doesn't work:

var q = { _id: { $oid: "5f3258cfbaaccedaa5dd2d96" } }
const result = await this.db.collection("persons").find(q).toArray();

Now,

var q = { _id: new mongo.ObjectID("5f3258cfbaaccedaa5dd2d96") };
JSON.stringify(q)

gives you : {"_id":"5f3258cfbaaccedaa5dd2d96"} and if you pass this to service A. You can not use it in service A as follows:

  const result = await this.db.collection("persons").find(qStr).toArray();

Or as,

  const result = await this.db.collection("persons").find(JSON.parse(qStr)).toArray();

Upvotes: 0

Views: 4112

Answers (2)

D. SM
D. SM

Reputation: 14480

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 = await this.db.collection("persons").find(deserializedQ).toArray();

Upvotes: 2

Thilo
Thilo

Reputation: 262494

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.

Upvotes: 2

Related Questions