-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
If you use Criteria#only to only return some fields from the database and then save a returned document, any fields not loaded will be set to their default values.
I am using Mongoid 2.4.7, Rails 3.2.2, and Mongodb 2.0.2.
Here is an example that demonstrates this:
class Widget include Mongoid::Document field :color, :type => String, :default => "blue" field :price, :type => Integer end Widget.delete_all Widget.create!(:color => "red", :price => 1) Widget.create!(:color => "green", :price => 2) puts "Initial state, colors are red and green:" Widget.all.each {|w| puts w.inspect} Widget.all.only(:price).each do |w| w.price += 10 w.save! end puts "\nAll colors have changed to blue after update:" Widget.all.each {|w| puts w.inspect}
Here is the output of the script:
Unable to find source-code formatter for language: code. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
Initial state, colors are red and green: #<Widget _id: 4f75d743acb93e02ac000001, price: 1, color: "red", _type: nil> #<Widget _id: 4f75d743acb93e02ac000002, price: 2, color: "green", _type: nil> All colors have changed to blue after update: #<Widget _id: 4f75d743acb93e02ac000001, price: 11, color: "blue", _type: nil> #<Widget _id: 4f75d743acb93e02ac000002, price: 12, color: "blue", _type: nil>
Appears to be related to MONGOID-1643. Although the exact repro steps described in that issue no longer trigger this problem, calling to_a or iterating over the elements as in the example above still expose the problem.