mongodb/mongoid · error · Mongoid::Errors::NoParent
Cannot persist embedded document
Error message
Cannot persist embedded document %{klass} without a parent document. What it means
Raised by insert_as_embedded when an embedded document is inserted without an associated parent document. Embedded documents can only be persisted through their parent's collection, so a missing _parent makes the insert impossible.
Solutions
- Set the parent association before saving, e.g. embed the document in its parent: parent.items << item
- Save the parent document, which cascades the insert to embedded children
- Redesign the model as a root-level (non-embedded) document if it should persist independently
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at lib/mongoid/persistable/creatable.rb:57 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/e517c6d01138c7c5.
Report an issue: GitHub.
Appendix: source
Thrown at lib/mongoid/persistable/creatable.rb:57
{ atomic_insert_modifier => { atomic_position => as_attributes } }
end
# Insert the embedded document.
#
# When the parent association is touchable (which is the default for
# +embedded_in+), the touch timestamp updates are merged into the
# same +update_one+ call that performs the insert. This avoids a
# second round-trip that the +after_save+ touch callback would
# otherwise issue.
#
# @api private
#
# @example Insert the document as embedded.
# document.insert_as_embedded
#
# @return [ Document ] The document.
def insert_as_embedded
raise Errors::NoParent.new(self.class.name) unless _parent
if _parent.new_record?
_parent.insert
else
selector = _parent.atomic_selector
operations = atomic_inserts
if _touchable_parent?
touches = _parent._gather_touch_updates(Time.current)
if touches.present?
operations['$set'] = (operations['$set'] || {}).merge(touches)
Threaded.begin_touch_merged(self)
end
end
_root.collection.find(selector).update_one(
positionally(selector, operations),
session: _sessionView on GitHub (pinned to 0da0e23d71)