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

Add a way for embedded documents to reference other embedded documents when they all share the same parent

    • Type: Icon: New Feature New Feature
    • Resolution: Unresolved
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 7.0.1
    • Component/s: Associations
    • Environment:
      All

      My current use case is that I want to create a tree-like data structure where all trees are documents in a Tree collection, and all nodes are embedded into that Tree document instead of belonging to a separate association, for performance reasons. The code at its simplest could look like this:

      class Tree
        include Mongoid::Document
          embeds_many :nodes
          field :name, type: String
      end
      class Node
        include Mongoid::Document
          embedded_in :trees
          has_many :subnodes, class_name: "Node"
          belongs_to :parent_node, class_name: "Node"
          field :name, type: String
      end

      Trying to create a node will raise a `Mongoid::Errors::MixedRelations` error. Which is fine, I can see why this wouldn't be currently possible.

      The feature request is to add a way to pass to the `belongs_to` a new argument, maybe name it `:through` or `:collection` or `:scope` or something, that lets it know that it shouldn't search or create new Nodes into a main Node collection, but within the embedded nodes of its own parent Tree class. Similarly for the has_many relation.

      The issue of having access to the root document of Node would be solved trivially as all Nodes will have direct access to their parent Tree

            Assignee:
            Unassigned Unassigned
            Reporter:
            camilo.forero3 Camilo Ernesto Forero Junco
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: