0

I have an Array field in my Mongoid model. I am then pushing a few elements to this array.

Do anyone know why my Array elements gets wrapped in hashes, all with the key "$each"?

class Website
  include Mongoid::Document
  include Mongoid::Timestamps

  field :visits, type: Array
end

website = Website.create
website.push(visits: Time.zone.now)
website.push(visits: Time.zone.now)

puts website.visits.inspect # => [{"$each"=>[2014-04-01 16:32:43 UTC]}, {"$each"=>[2014-04-01 16:32:43 UTC]}]
Cjoerg
  • 1,271
  • 3
  • 21
  • 63
  • 1
    Why `website.push` instead of `website.visits.push`? – mu is too short Apr 01 '14 at 16:13
  • Becuase of the documentation [here](http://two.mongoid.org/docs/persistence/atomic.html#push). But your solution does fix my issue. Only downside is that I have to call `website.save` after the push. Any idea if this can be avoided? – Cjoerg Apr 01 '14 at 16:31
  • Those docs are for Mongoid2, you're using Mongoid4. Maybe you should look at more recent docs: http://rubydoc.info/github/mongoid/mongoid/frames – mu is too short Apr 01 '14 at 16:43
  • Ah, right you are. Thanks. Feel free to put your answer in, then I will approve it. – Cjoerg Apr 01 '14 at 16:46
  • I don't know Mongoid4 that well (still using 3), feel free to answer your own question. – mu is too short Apr 01 '14 at 16:59

0 Answers0