Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-965

ManyToMany#nullify causing memory bloat

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.1.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      The current implementation of references_and_referenced_in_many#nullify method is causing crazy memory bloats if you have a few hundred referenced records you want to nullify.

      current code:

              def nullify
                load! and target.each do |doc|
                  base.send(metadata.foreign_key).delete(doc.id)
                  dereference(doc)
                end
                target.clear
              end
      

      This could be extremely painful if you have hundreds or thousands of referenced objects.

      It is also totally unnecessary to load all related records and individually remove/dereference them, when we already know that we don't want any related object to reference to base.

      Here's my implementation that does not cause memory bloat and also removes all records making only one call:

          class ManyToMany < Referenced::Many
              def nullify
                metadata.klass.collection.update({metadata.inverse_foreign_key => {"$in" => [base.id] }}, {"$pull" => {metadata.inverse_foreign_key => base.id}}, :multi => true)
                base.update_attribute metadata.key, []
              end
           end
      

            Assignee:
            durran Durran Jordan
            Reporter:
            computadude Mark Ronai
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: