[英]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
实际上是两个步骤:
as_json
to get a Hash. as_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.