-
Type:
Bug
-
Resolution: Unresolved
-
Priority:
Minor - P4
-
None
-
Affects Version/s: 9.1.0
-
Component/s: None
-
None
Due to memoization on _descendants not being reset during embedded relation clear, mongoid will re-insert cleared documents sometimes:
require "bundler/inline" gemfile do source "https://rubygems.org" gem "mongoid", "9.1.0" end require "mongoid" Mongoid.configure do |config| config.clients.default = { hosts: [ENV.fetch("MONGO_HOST", "localhost:27017")], database: "mongoid_embeds_many_clear_repro", options: { direct_connection: true } } end Mongoid.logger.level = Logger::WARN Mongo::Logger.logger.level = Logger::WARNclass Root include Mongoid::Document embeds_one :section end class Section include Mongoid::Document embedded_in :root embeds_many :items end class Item include Mongoid::Document embedded_in :section field :name, type: String end Root.collection.dropdef stored_item_names(root) doc = Root.collection.find(_id: root.id).first Array(doc && doc.dig("section", "items")).map { |item| item["name"] } end root = Root.create! section = root.build_section section.items.build(name: "one") section.items.build(name: "two") root.save! # memoizes the root's _descendants while building the atomic update puts "after build + save: #{stored_item_names(root).inspect}" # => ["one", "two"] root.section.items.clear puts "after clear: #{stored_item_names(root).inspect}" # => [] ($unset was issued) puts "in memory: #{root.section.items.map(&:name).inspect}" # => [] root.save! puts "after save: #{stored_item_names(root).inspect}" # => ["one", "two"] (!!) puts "in memory: #{root.section.items.map(&:name).inspect}" # => [] puts "reloaded: #{Root.find(root.id).section.items.map(&:name).inspect}" # => ["one", "two"]