简体   繁体   English

如何将杂项文档转换为JSON,从而去除嵌入式文档ID,但保留主文档ID?

[英]How can I turn a mongoid document into JSON stripping out embedded document ids, but keeping the main document id?

I have a document that has some embedded documents (and some of those have further embedded documents). 我有一个文档,其中包含一些嵌入式文档(其中一些文档还包含其他嵌入式文档)。

I want to return the document content as JSON but without all the IDs for the embedded documents. 我想以JSON格式返回文档内容,但没有嵌入文档的所有ID。

I can do this: mydoc.to_json(:except => :_id) but that strips all BSON IDs, including the one for mydoc. 我可以这样做:mydoc.to_json(:except =>:_id),但这会除去所有BSON ID,包括用于mydoc的ID。

Is there some other way to only strip the embedded document IDs? 还有其他方法可以去除嵌入式文档ID吗?

Keep in mind that to_json is actually two steps here: 请记住, to_json实际上是两个步骤:

  1. Call as_json to get a Hash. 调用as_json以获取哈希。
  2. Convert that Hash to a string of JSON. 将该哈希转换为JSON字符串。

So you could use as_json instead of to_json to build a Hash without any _id s, then put the _id you care about back in, and finally convert to JSON: 因此,您可以使用as_json而不是to_json来构建不带任何_id的哈希,然后将您关心的_id放回去,最后转换为JSON:

mydoc.as_json(:except => :_id).merge('_id' => mydoc.id).to_json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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