mongodb/mongoid · error · Mongoid::Errors::DocumentNotFound
Document not found for class
Error message
Document not found for class %{klass} with attributes %{attributes}. What it means
update_nested_relation failed to find the referenced document when reparenting is not allowed (or the HABTM lookup missed), so the id given in nested attributes does not correspond to an existing persisted document.
Solutions
- Ensure the ids in nested attributes belong to existing documents of the association class
- Enable Mongoid.allow_reparenting_via_nested_attributes if pushing existing documents is intended
- Rescue Mongoid::Errors::DocumentNotFound to handle stale ids gracefully
Defensive patterns
Strategy: try-catch
When it happens
Trigger: Thrown at lib/mongoid/association/nested/many.rb:210 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of mongodb/mongoid@0da0e23d71 (2026-08-23).
Data as JSON: /api/errors/76da8dc1259b0720.
Report an issue: GitHub.
Appendix: source
Thrown at lib/mongoid/association/nested/many.rb:210
elsif association.embedded?
raise Errors::DocumentNotFound.new(association.klass, id)
elsif association.is_a?(Association::Referenced::HasAndBelongsToMany) || Mongoid.allow_reparenting_via_nested_attributes?
unless destroyable?(attrs)
Mongoid::Warnings.warn_reparenting_via_nested_attributes if Mongoid.allow_reparenting_via_nested_attributes?
# push existing document to association
doc = association.klass.unscoped.find(converted)
# find returns nil instead of raising when
# Mongoid.raise_not_found_error is false; a missing document
# must still be an error here, consistent with the other
# not-found branches.
raise Errors::DocumentNotFound.new(association.klass, id) if doc.nil?
update_document(doc, attrs)
existing.push(doc)
end
else
raise Errors::DocumentNotFound.new(association.klass, { _id: id, association.foreign_key => parent.id })
end
parent.children_may_have_changed!
end
end
end
end
end
View on GitHub (pinned to 0da0e23d71)