How do I exclude fields from an embedded document in Mongoid?

落花浮王杯 提交于 2019-12-06 20:06:11

问题


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)

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?

Here are my models:

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

回答1:


You'll need to use Mongoid's without method. Something like this should do the trick:

Post.without(:_id, :body, "tags._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.

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.



来源:https://stackoverflow.com/questions/6419033/how-do-i-exclude-fields-from-an-embedded-document-in-mongoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!