简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM