Rails Mongodb default value

The database is mongodb connected to rails. Suppose there are already some records in the db. Now, I add a new boolean field in the model. What will become the value of this field for the already existing records ? Is it nil or true or false ? Thanks in advance.

Upvotes: 0

Views: 293

Answers (1)

Haumer
Haumer

Reputation: 559

For existing records that field should return nil

Example

def SomeModel
  field :foo, type: :boolean
  field :bar, type: :boolean, default: true
end

then assuming you have previous records:

SomeModel.first.foo #=> nil
SomeModel.first.bar #=> true

If the field is more complex, you can always make a migration to fix the value for any records whose fields dont match what you want.

EDIT: migrations are typically associated with relational databases but for the purpose of running them once and keeping the code in the codebase it might be a solution

Upvotes: 1

Related Questions