I’m trying to run an update on my data in the rails console and for some reason, updating one attribute causes Mongoid to set the other attributes to null:
1.9.3p194 :044 > User.first().cart.cartitems
=> [#<Cartitem _id: 5047eef3c8bafa761100001a, _type: nil, quantity: 1000, scentid: 1>]
1.9.3p194 :047 > User.first().cart.cartitems.where(scentid:1).update(quantity:100)
=> nil
1.9.3p194 :048 > User.first().cart.cartitems
=> [#<Cartitem _id: 5047ef65c8bafa761100001c, _type: nil, quantity: 100, scentid: nil>]
Notice how the scentid is set to nil. I’ve also tried using .set(:quantity, 100) but this does not persist when I query the cartitems again.
Is this normal behavior?
Thanks!
is it possible that you’re running the pure MongoDB ruby driver .update() method instead of the Mongoid persistence methods? If so, the observed behavior would be expected. update() rewrites the full document, as stated here: http://api.mongodb.org/ruby/current/file.TUTORIAL.html#Updating_Documents_with_update
You could use the $set operator with:
Or try Mongoid’s
update_attributes()instead or any other suitable persistence method from: http://mongoid.org/en/mongoid/docs/persistence.html#atomic