Mongo JSON文档-> JSON-> BSON

发布于 2024-09-13 12:49:35 字数 1478 浏览 7 评论 0 原文

我正在使用 Node.js 构建一个使用 mongodb 的 Web 套接字服务器。

我使用 node-mongodb-native 作为访问 mongo db 的库。

当我对数据库中的对象调用 console.log(sys.inspect(item)) 时,我得到如下所示的内容:

{ _id: { id: 'L?#&\u008e\u00ad\u000e\u008f\u0014\u0005\u0000\u0000' }
, y: 3
, favorite_color: 'orange'
, x: 14766
}

所以我猜测 id 是 mongo 使用的 BSON 对象 id。

我需要使用 JSON 将此对象发送到客户端 Web 浏览器,让他们对其执行一些操作,然后将其发送回服务器。

当我 JSON.stringify(item) 时,我得到如下所示的内容:

{"_id":"4c3f23268ead0e8f14050000","y":3,"favorite_color":"orange","x":14766}

因此 id 已转换为某种十六进制编码的字符串。如果我将其发送给客户端,客户端将其发回,我现在需要在数据库中更新它。我运行 JSON.parse(item) 使其成为一个普通对象,但它仍然看起来像这样:

{ _id: '4c3f23268ead0e8f14050000'
, y: 3
, favorite_color: 'orange'
, x: 14766
}

并且 _id 不能用于在 mongodb 中查找。

如何将其转换回可用于在 mongo 上查找的格式?

--update--

有趣的是,我可以使用 findOne({_id:item._id}, collection) 来获取文档,但如果我这样做:

findOne({_id:{id : item._id.id}}, collection)

我没有收到结果。我想 mongo _id 对象有一些特别之处。

{_id:item._id}{_id:{id : item._id.id}} 转储时看起来像这样:

{ _id: { id: 'L?#&\u008e\u00ad\u000e\u008f\u0014\u0005\u0000\u0000' } }

--另一个更新已解决 ---

集成测试文件中存在一些对象 ID 操作。

objectId = new mongo.ObjectID.createFromHexString('47cc67093475061e3d95369d'); 将给出我正在寻找的_id。

objectId.toHexString() 将返回类似于“47cc67093475061e3d95369d”的十六进制字符串

I am working with Node.js to build a web socket server that uses mongodb.

I am using node-mongodb-native as the library to access mongo db.

When I call console.log(sys.inspect(item)) on an object from the db I get something that looks like this:

{ _id: { id: 'L?#&\u008e\u00ad\u000e\u008f\u0014\u0005\u0000\u0000' }
, y: 3
, favorite_color: 'orange'
, x: 14766
}

so I am guessing the id is the BSON object id that mongo uses.

I need to send this object to the client web browser using JSON, have them do some stuff to it, and then send it back to the server.

When I JSON.stringify(item), I get something that looks like this:

{"_id":"4c3f23268ead0e8f14050000","y":3,"favorite_color":"orange","x":14766}

So the id has been turned into some hex encoded string. If I send it to the client, and the client sends it back, I now need to update it in the db. I run JSON.parse(item) to get it to be a normal object, but it still looks like this:

{ _id: '4c3f23268ead0e8f14050000'
, y: 3
, favorite_color: 'orange'
, x: 14766
}

and that _id can't be used to look up in mongodb.

How can I convert it back to a format that will be able to be used for lookups on mongo?

--update--

Interestingly I can use findOne({_id:item._id}, collection) to get the document, but if I do this:

findOne({_id:{id : item._id.id}}, collection)

I don't receive a result. I guess there is something special about the mongo _id object.

Both {_id:item._id} and {_id:{id : item._id.id}}
when dumped out look like this:

{ _id: { id: 'L?#&\u008e\u00ad\u000e\u008f\u0014\u0005\u0000\u0000' } }

--Another update RESOLVED---

There was some object id manipulation in an integration test file.

objectId = new mongo.ObjectID.createFromHexString('47cc67093475061e3d95369d');
will give the _id that I am looking for.

objectId.toHexString()
will return the hex string that looks like '47cc67093475061e3d95369d'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枕头说它不想醒 2024-09-20 12:49:45

好吧,我在使用 python 客户端时遇到了同样的错误。但我将澄清两种语言的成就结果。

首先,MongoDB返回的_id是BSON对象。意思是 JSON 的二进制编码序列化,更多信息请参见此链接:BSON

假设您想要插入数据以下字段:

params = {
   "y":3,
   "favorite_color":"orange",
   "x":14766
}
client.connect(url, function(err, db) {
  var dbo = db.db("test_database");
dbo.collection("my_collection").insertOne(params, function(err, res) {
 if (err) throw err;
   console.log("inserted document",JSON.stringify(res));
    db.close();
   });
});

返回对象结果,例如"_id":"5e95abf57b59b448bb22dedf"

定义ObjectId,可以方便地使用findOne、updateOne方法。

const {ObjectId} = require('mongodb');
client.connect(url, function(err, db) {
  var dbo = db.db("test_database");
 var myquery = { "_id": ObjectId("5e95abf57b59b448bb22dedf") } ;

    dbo.collection("my_collection").findOne(myquery, function(err, result) {
      if (err) throw err;
      console.log(result);
   });

});

更新:

client.connect(url, function(err, db) {
  var dbo = db.db("test_database");
   var myquery = { "_id": ObjectId("5e95abf57b59b448bb22dedf") } ;
    var newvalues = { $set: {favorite_color: "red", y: "14760" } };
    dbo.collection("my_collection").updateOne(myquery, newvalues, function(err, res) {
      if (err) throw err;
      console.log("1 document updated");
      db.close();
    });
});

对于 python:

让我们以此结果为例: {'_id':ObjectId('5e95a18dcae4a4a005e14bd8')}


from bson.json_util import loads as bson_loads, dumps as bson_dumps 
import json


#you should dump it then load it 
result = document = json.loads(bson_dumps(document))
{ "$set": {"status": False}}

#update:
db["my_collection"].update_one({ "_id": result},new_value)  

#find_one:
db["my_collection"].find_one({ "_id": resultjs})

有关使用 python MongoDB 客户端(电机)的更多信息,我创建了 要点

Well, I was stuck with the same error while working with python client. But I will clarify the accomplishment result for both languages.

Firstly the _id MongoDB returns is the BSON object. Meaning bin­ary-en­coded seri­al­iz­a­tionfor of JSON, more in this link: BSON

Let's say you want to insert data with the following fields:

params = {
   "y":3,
   "favorite_color":"orange",
   "x":14766
}
client.connect(url, function(err, db) {
  var dbo = db.db("test_database");
dbo.collection("my_collection").insertOne(params, function(err, res) {
 if (err) throw err;
   console.log("inserted document",JSON.stringify(res));
    db.close();
   });
});

it return object result, for instance "_id":"5e95abf57b59b448bb22dedf"

Defining ObjectId, you can easily use findOne, updateOne methods.

const {ObjectId} = require('mongodb');
client.connect(url, function(err, db) {
  var dbo = db.db("test_database");
 var myquery = { "_id": ObjectId("5e95abf57b59b448bb22dedf") } ;

    dbo.collection("my_collection").findOne(myquery, function(err, result) {
      if (err) throw err;
      console.log(result);
   });

});

update:

client.connect(url, function(err, db) {
  var dbo = db.db("test_database");
   var myquery = { "_id": ObjectId("5e95abf57b59b448bb22dedf") } ;
    var newvalues = { $set: {favorite_color: "red", y: "14760" } };
    dbo.collection("my_collection").updateOne(myquery, newvalues, function(err, res) {
      if (err) throw err;
      console.log("1 document updated");
      db.close();
    });
});

For python:

let's take this result as an example: {'_id':ObjectId('5e95a18dcae4a4a005e14bd8')}


from bson.json_util import loads as bson_loads, dumps as bson_dumps 
import json


#you should dump it then load it 
result = document = json.loads(bson_dumps(document))
{ "$set": {"status": False}}

#update:
db["my_collection"].update_one({ "_id": result},new_value)  

#find_one:
db["my_collection"].find_one({ "_id": resultjs})

For more to work with python MongoDB client(motor) I have created Gist

痞味浪人 2024-09-20 12:49:43

我的猜测是 sys.inspect 解释 ObjectId 作为包含 id 属性的对象。这就是你在垃圾场看到的。

MongoDB 将 ObjectId 视为 12 字节的二进制值,而不是对象。所以 MongoDB 不知道任何 id 属性。这就是为什么以下查询不会产生结果:

findOne({_id: {id: item._id.id}}, collection)

以下查询确实有效,因为它只是将两个值视为二进制值:

findOne({_id: item._id}, collection)

My guess is that sys.inspect interprets an ObjectId as an object containing an id property. That's what you're seeing in the dump.

MongoDB treats the ObjectId as a 12-byte binary value, not as an object. So MongoDB doesn't know about any id property. That's why the following query yields no result:

findOne({_id: {id: item._id.id}}, collection)

The following does work, as it just treats both values as binary values:

findOne({_id: item._id}, collection)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文