Write conflict error when accessing embedded documents via [] operator after direct DB update

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Unresolved
    • Priority: Major - P3
    • None
    • Affects Version/s: 8.1.11, 8.0.11, 9.0.8
    • Component/s: Persistence
    • None
    • Ruby Drivers
    • None
    • None
    • None
    • None
    • None
    • None

      After upgrading to Mongoid 8, accessing embedded documents using the [] operator on a model created without the embedded default, and then saving, causes a write conflict error. It appears to be related to the change https://github.com/mongodb/mongoid/pull/5284.

       

      #!/usr/bin/env ruby
      
      require 'logger'
      require 'bundler/inline'
      
      gemfile do
        source 'https://rubygems.org'
        gem "mongoid", "#{ENV["MONGOID_VERSION"] || '8.0.10'}"
        gem "debug", "~> 1.7"
        gem "minitest", require: "minitest/autorun"
      end
      
      require 'mongoid'
      
      Mongoid.configure { |c| c.clients.default = { hosts: ['localhost'], database: 'test' } }
      puts Mongoid::VERSION
      
      class Address
        include Mongoid::Document
        include Mongoid::Attributes::Dynamic
        field :city, type: String, default: "Unknown"
        embedded_in :person
      end
      
      class Person
        include Mongoid::Document
        field :name, type: String
        embeds_many :addresses
      end
      
      Person.delete_all
      Address.delete_all
      
      p = Person.create!(name: "John")
      result = Person.collection.find(:_id => p.id)
              .update_one({:$push => {:addresses => {:_id => BSON::ObjectId.new}}})
      p1 = Person.find(p.id)
      p1[:addresses].is_a?(Array)
      puts p1.addresses[0].changes.inspect # {"city"=>[nil, "Unknown"]}
      puts p1.changes.inspect # {"addresses"=>[[{"_id"=>BSON::ObjectId('68d2c593fa49abf8f51c1cad')}], [{"_id"=>BSON::ObjectId('68d2c593fa49abf8f51c1cad'), "city"=>"Unknown"}]]}
      p1.save! # [40]: Updating the path 'addresses.0.city' would create a conflict at 'addresses' (on localhost, legacy retry, attempt 1) (Mongo::Error::OperationFailure)
      

       

            Assignee:
            Unassigned
            Reporter:
            Joe Lim
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: