Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude fields from document in mongoid?

I have a Record model with many dynamic attributes. I want to make a request to the model an send the response as JSON to the client. But i want to exclude fields like _id and all foreign_keys in this model.

I found an interessting answer how to exclude the values of some keys: How do I exclude fields from an embedded document in Mongoid?, but the keys in the response still exists.

I got:

{
 "_id": 1,
 "name": "tom"
}

And the without method makes:

{
  "_id": nil,
 "name": "tom"
}

But i want:

{
 "name": "tom"
}

Is it possible to remove or exclude some keys and the values from the result?

like image 741
Mindbreaker Avatar asked Jun 20 '13 10:06

Mindbreaker


2 Answers

You don't want to remove fields from the mongoid document, what you want to do is remove fields from the generated json. In your controller, do

render :json => @model.to_json(:except => :_id)

Documentation for the to_json method http://apidock.com/rails/ActiveRecord/Serialization/to_json

like image 50
RedXVII Avatar answered Sep 29 '22 19:09

RedXVII


taken from the mongodb documentation at: http://docs.mongodb.org/manual/reference/method/db.collection.find/

Exclude Certain Fields from the Result Set The following example selects documents that match a selection criteria and excludes a set of fields from the resulting documents:

db.products.find( { qty: { $gt: 25 } }, { _id: 0, qty: 0 } ) The query returns all the documents from the collection products where qty is greater than 25. The documents in the result set will contain all fields except the _id and qty fields, as in the following:

{ "item" : "pencil", "type" : "no.2" }
{ "item" : "bottle", "type" : "blue" }
{ "item" : "paper" }

i suppose mongoid is setting the _id attribute to nil since mongoid models have a defined set of attributes (even if they are dynamic, _id, _type etc are defined). maybe you can try it with the mongodb driver.

but i think RedXVII answer is the more practical way to go

like image 43
Dominik Goltermann Avatar answered Sep 29 '22 19:09

Dominik Goltermann