如何在 nodejs 中将 MongoDb ObjectId(“uniqueid") 序列化为 JSON? [英] How serialize MongoDb ObjectId("uniqueid") to JSON in nodejs?

查看:32
本文介绍了如何在 nodejs 中将 MongoDb ObjectId(“uniqueid") 序列化为 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个查询构建器服务 B,它在调用时会输出 mongo db 查询.此查询由服务 A 接收,并按原样使用 mongo db 官方 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.

我如何发送类似:

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

从服务 B 到服务 A?

from service B to service A?

以下工作完全正常:

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

以下不起作用:

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

现在,

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

给你:{"_id":"5f3258cfbaaccedaa5dd2d96"} 并且如果你把它传递给服务 A.你不能在服务 A 中使用它,如下所示:

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

或者作为,

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

推荐答案

您需要:

  • 将您的文档序列化为一端的扩展 json
  • 将您的文档从扩展的 json 反序列化为另一端的语言原生数据结构

https://github.com/mongodb/js-bson#node-no-bundling 了解如何序列化和反序列化.

See https://github.com/mongodb/js-bson#node-no-bundling for how to serialize and deserialize.

您不能像您尝试做的那样,将扩展的 json 类型带注释的哈希提供给需要本机类型的驱动程序函数(基本上,除了专门解析扩展 json 的那些之外,基本上都是这些类型).

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

这篇关于如何在 nodejs 中将 MongoDb ObjectId(“uniqueid") 序列化为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆