I have model as follows:
class User
include Mongoid::Document
field :name
end
After saving a few user objects to the database I added some more fields:
class User
include Mongoid::Document
include Mongoid::Timestamps::Created
field :name
field :birthdate
end
Now, I expect I can use the following snippet:
@user = User.all
@user.each do |u|
puts u.name
puts u.birthdate.strftime(#someFormat)
puts u.created_at.strftime(#someFormat)
end
Unfortunately, because my old user objects don’t have birthdate keys, I receive this error: strftime called on nil class.
Question:
- How can I handle such cases with Mongoid? In MySQL, when a column is added it gets added to old rows as well. But if I see in MongoDB, it doesn’t add new fields as keys for old data.
- This problem also exists with the
created_atfield as old data doesn’t have that field either.
I am looking for good way to solve this, checking for nil conditions each time is not a scalable option because the number of fields will continue increasing.
You could also add a default to your new field, which would give all your old records a fallback value.
You can update your models which are missing
created_atvalues, but just running something simple in your rails console: