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
You’ll need to use Mongoid’s
withoutmethod. Something like this should do the trick:Which will return all your post titles only, as well as all their embedded tags and no
_idfields for either Posts or Tags.I noticed also that you have
field :tags, :type => Arraydefined on your Post model – which I believe is redundant. Usingembeds_manysets that field up for you automatically.