Exclude fields from document in mongoid?

I have a recording model with many dynamic attributes. I want to make a request to the model to 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 interesting answer on how to exclude the values ​​of some keys: How to exclude fields from an embedded document in Mongoid? but the keys in the answer still exist.

I got:

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

And the without method does:

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

But I want:

 { "name": "tom" } 

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

+4
source share
2 answers

You do not want to remove fields from the mongoid document, what you want to do is remove the 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

+6
source

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

Exclude certain fields from the result set. In the following example, documents that match the selection criteria are selected and excludes the set of fields from the resulting documents:

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

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

Suppose mongoid sets the _id attribute to nil, since mongoid models have a specific set of attributes (even if they are dynamic, _id, _type, etc.). perhaps you can try it with the mongodb driver.

but I think RedXVII's answer is a more practical way to go

+1
source

Source: https://habr.com/ru/post/1487269/


All Articles