Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7084143
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T07:15:54+00:00 2026-05-28T07:15:54+00:00

I have a lot of optional fields in Mongoid, like: field :key, type: String

  • 0

I have a lot of optional fields in Mongoid, like:

  field :key, type: String             
  field :element, type: String         
  field :rect, type: Array             

If I return a json of this model with only one of them filled I get null values on all the other fields. How can I remove those fields?

My model has nested attributes, which means null values can be on several levels.

Clarifications:

I need a way to remove null fields from the json representation of a model, including null fields in all nested attributes.

Code Example:

1.9.3-p0 :005 > u=Muse.new(:key=>'ram').to_json
 => "{\"_id\":\"4f1ced749c2ee4219d000003\",\"element\":null,\"key\":\"ram\",\"rect\":null}" 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T07:15:54+00:00Added an answer on May 28, 2026 at 7:15 am

    By default mongoid has the ability to remove empty fields. If you let some fields empty, mongoid will removes them on insert.

    in the below example, I left out the fields element & rect

    class User
      include Mongoid::Document
    
        field :key, type: String             
        field :element, type: String         
        field :rect, type: Array       
    
        embeds_one :home  
    end
    >> u=User.new(:key=>'ram').to_json
    => "{"_id":"4f1c3722b356f82e4a000001","_type":"key":"ram"}"
    

    and it works perfectly. But if you put a nil value in the field

    >> u=User.new(:key=>'ram',:element=>nil).to_json
    => "{"_id":"4f1c3722b356f82e4a000001","_type":"User","key":"ram","element":null}"
    

    It gets inserted. I assume that’s the exact problem in your code. So you can work around this by converting JSON hash representation using as_json and remove the nil fields

    x=u.as_json.reject! {|k,v| v.nil?}
    => "{"_id":"4f1c3722b356f82e4a000001","_type":"User","key":"ram"}"
    

    But to go to the inner levels, you cannot use as_json. check the below code

      >>h=Home.new(:address=>'xxxx',:dummy=>nil)
      >>u.home = h 
      >>x=u.as_json.reject! {|k,v| v.nil?}
      =>{"_id"=>BSON::ObjectId('4f1c39b4b356f82e4a000003'), "_type"=>"User","key":"ram","home"=>#<Home _id: 4f1c3c5db356f82e4a000004,address:'xxxx' , dummy: nil >}
    

    Now you see the field dummy inside the embedded doc house is still with nil. so my best advice is Dont put the nil values in db at all. To do that put a before_save callback on your models (embedded too) and remove the empty fields.

    Also I will show you how to remove nil fields from nested objects too. Use it if there is no other way

    We can use attributes of mongoid model to get the hash representation of the object including the nested levels

    x=u.attributes
    => {"_id"=>BSON::ObjectId4f1c39b4b356f82e4a000003,"key"=>"ram","element"=>nil,"home"=>{"address"=>"xxxx", "_id"=>BSON::ObjectId4f1c3c5db356f82e4a000004,"dummy"=>nil}}
    

    and you have to find is there any Hash inside the mongoid object, if one, we have to use the reject! {|k,v| v.nil?} on that Hash too

    to put together all

    def to_json(obj)
         obj.reject! {|k,v| v.nil?}
         obj.find_all {|x| x[1].class==BSON::OrderedHash}.each do |arr| 
               obj[arr[0]] = to_json(arr[1])    
         end
         obj     
    end
    

    and call this with attributes of the model,

     >> to_json u.attributes
     => {"_id"=>BSON::ObjectId4f1c39b4b356f82e4a000003,"key"=>"ram","home"=>{"address"=>"xxxx", "_id"=>BSON::ObjectId4f1c3c5db356f82e4a000004}}
    

    Thats all. Hope it helps

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a function that looks like the following, with a whole lot of
Right now I have classes like: abstract class Record { // Required fields val
I have an index whose documents have two fields (actually more like 800 fields
I noticed that a lot of scripts have these type of comments: /** *
I have a form on a website which has a lot of different fields.
We have lot of object with this kind of design : Interface and several
I have a requirement to use date picker in my applicaiton. I have lot
At the moment, I have lot's of Java which does all kind of nifty
Have a lot of unnecessary results using contains() method in my query. Don't tell
We have a lot of open discussions with potential clients, and they ask frequently

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.