as request on MONGOID-2215 this is the counter cache implementation for mongoid.
It should work simliar as the Rails activerecord counter cache, which increment the number of children when A new children is created and has a foreign_key to its parent.
Example:
class Person include Mongoid::Document has_many :pets end class Pet include Mongoid::Document belongs_to :person, counter_cache: true end
person.pets.create! #should increment person.pets_count
pet = Pet.new
pet.person = person
pet.save #should incremente person.pets_count
pet.destroy # should decrement person.pets_count
pet.delete # should NOT decrement person.pets_count
Also added some useful methods like
Unable to find source-code formatter for language: person. 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
.reset_counters(person.id, :pets)
and
Unable to find source-code formatter for language: person. 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
.update_counters(person.id, pets_count: 5)