如何从Mongoid中的嵌入式文档中排除字段? [英] How do I exclude fields from an embedded document in Mongoid?
问题描述
我有一个带有嵌入式标签的Post文档.有时我只显示帖子的标题及其标签.在这种情况下,我会在mongoid中使用以下查询:
I have a Post document that has embedded tags. Sometimes I display only the title of a post and its tags. In those cases, I use the following query in mongoid:
Post.only(:title).find(id)
然后我将查询结果作为json发送到客户端.不幸的是,标签的bson ID使json变得比我需要的大得多. 如何从查询中排除"_id"字段?
I then send the results of the query as json to the client. Unfortunately, the tag's bson id makes the json much larger than I need it to be. How do I exclude the "_id" field from the query?
这是我的模特:
class Post
include Mongoid::Document
field :title, :type => String
field :body, :type => String
field :tags, :type => Array
embeds_many :tags
end
class Tag
include Mongoid::Document
field :tag, :type => String
field :type, :type => String
embedded_in :post
end
推荐答案
您将需要使用Mongoid的without
方法.这样的事情应该可以解决问题:
You'll need to use Mongoid's without
method. Something like this should do the trick:
Post.without(:_id, :body, "tags._id")
将仅返回您所有的帖子标题,以及它们的所有嵌入式标签,并且不返回"_id
"字段用于帖子"或标签".
Which will return all your post titles only, as well as all their embedded tags and no _id
fields for either Posts or Tags.
我还注意到您在Post模型上定义了field :tags, :type => Array
-我认为这是多余的.使用embeds_many
会自动为您设置该字段.
I noticed also that you have field :tags, :type => Array
defined on your Post model - which I believe is redundant. Using embeds_many
sets that field up for you automatically.
这篇关于如何从Mongoid中的嵌入式文档中排除字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!