Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exclude fields from an embedded document in 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)

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
like image 946
stevendaniels Avatar asked Jun 21 '11 00:06

stevendaniels


1 Answers

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.

like image 58
theTRON Avatar answered Oct 18 '22 15:10

theTRON