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

Embedded documents fetch using `only` raises MissingAttributeError

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 7.1.2
    • Component/s: Query
    • None
    • Environment:
      Rails 6.0.3.2, Ruby 2.7.1, MongoDB 4.2.8

      We migrated from Mongoid 7.0.8 to 7.1.2. After the migration, accessing any attribute on the embedded document after fetching the parent with Model.only(:attribute_name) raises MissingAttributeError even though the embedded document was not fetch with only. Looking at <embedded_document>.attributes show that the attributes are fetched.
      The following code show the error:

      class Parent
        include Mongoid::Document
        include Mongoid::Timestamps
      
        field :first_name, type: String
        field :last_name, type: String
      
        embeds_many :children
      end
      
      class Child
        include Mongoid::Document
        include Mongoid::Timestamps
      
        field :first_name, type: String
        field :last_name, type: String
      
        embedded_in :parent
      end
      
      child = Child.new(first_name: 'xc', last_name: 'yc')
      parent = Parent.new(first_name: 'xp', last_name: 'yp')
      parent.children
      parent.children << child
      parent.save
      pa = Parent.where(first_name: 'xp').only(:children).first
      # this line worksputs pa.children[0].attributes[:_id] # prints the id of the document
      # this line raises MissingAttributeErrorpa.children[0]._id # raises MissingAttributeError
      

            Assignee:
            emily.giurleo@mongodb.com Emily Giurleo (Inactive)
            Reporter:
            udi@honeybook.com Udi Cohen
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: