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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With