Search code examples
ruby-on-rails-3mongodbmongodb-ruby

Rails 3 + MongoDB: Render Json Without a Field


    render :json => @bs.to_a.to_json, :except => ["completo"]      

I want to render everything to json except the field "completo". That should be working but given that I need to do ".to_a" and ".to_json", that stopped working. Is there a way to revert that?

Thanks


Solution

  • Assuming that @bs is a MongoDB Cursor, do the following:

    @bs = @bs.to_a.map { |obj| obj.delete("completo"); obj }
    render :json => @bs.to_json
    

    In summary:

    1. Make it an array.
    2. Remove the completo key from every item in the array, making sure we return the item itself at the end of the map
    3. Render as before.