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

count is 0 for populated embeds_many on unsaved host model

    • Type: Icon: Bug Bug
    • Resolution: Works as Designed
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Associations
    • Labels:
      None

      Given an embeds_many association, if a host model is unsaved and there are instances added to the embeds_many association, length on the association returns the correct number of instances but count returns 0. Once the host model is saved count behaves correctly:

      class School
        include Mongoid::Document
        
        embeds_many :students
      end
      
      class Student
        include Mongoid::Document
        
        embedded_in :school
      end
      
      a = School.new(students: [Student.new])
      a.students.length
      a.students.count
      a.save!
      a.students.length
      a.students.count
      
      irb(main):033:0> a = School.new(students: [Student.new])
      => #<School _id: 5dacbb6b026d7c52b820f0bf, >
      irb(main):034:0> a.students.length
      => 1
      irb(main):035:0> a.students.count
      => 0
      irb(main):036:0> a.save!
      D, [2019-10-20T15:54:19.832664 #21176] DEBUG -- : COMMAND | localhost:14422 | mongoid.insert | STARTED | {"insert"=>"schools", "ordered"=>true, "documents"=>[{"_id"=>BSON::ObjectId('5dacbb6b026d7c52b820f0bf'), "students"=>[{"_id"=>BSON::ObjectId('5dacbb6b026d7c52b820f0c0')}]}], "$clusterTime"=>{"clusterTime"=>#<BSON::Timestamp:0x0000563ac5a5d448 @seconds=1571252182, @increment=1>, "signature"=>{"hash"=><BSON::Binary:0x47405212035300 type=generic data=0x0000000000000000...>, "keyId"=>0}}, "txnNumber"=>#<BSON::Int64:0x0000563ac6af12a0 @integer=1>, "lsid"=>{"id"=><BSON::Binary:0x47405220474300 type=uuid data=0x8875052a35694b8b...>}}
      D, [2019-10-20T15:54:19.840960 #21176] DEBUG -- : COMMAND | localhost:14422 | mongoid.insert | SUCCEEDED | 0.007746822s
      => true
      irb(main):037:0> a.students.length
      => 1
      irb(main):038:0> a.students.count
      => 1
      irb(main):039:0> 
      

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: