Skip to content

Inline Embedded Schemas #280

@numso

Description

@numso

If I'm using Mongo.Collection and I want to define a schema with lots of nesting, I end up having to kind of do it backwards. In this example a Form has Fields has Options. But I need to define the schema first for Option then Field then Form.

defmodule MyApp.Forms.Form do
  use Mongo.Collection

  defmodule Field do
    use Mongo.Collection

    defmodule Option do
      use Mongo.Collection
  
      document do
        attribute :label, String.t()
        attribute :value, String.t()
      end
    end
  
    document do
      attribute :id, String.t()
      attribute :label, String.t()
      attribute :type, String.t()

      embeds_many :options, Option, default: []
    end
  end

  collection "forms" do
    attribute :name, String.t()
    attribute :description, String.t()

    embeds_many :fields, Field, default: []
  end
end

Ecto supports an inline embedding syntax to make that look cleaner. Would you be open to a PR that added a similar syntax? Something like this:

defmodule MyApp.Forms.Form do
  use Mongo.Collection

  collection "forms" do
    attribute :name, String.t()
    attribute :description, String.t()

    embeds_many :fields, Field, default: [] do
      attribute :id, String.t()
      attribute :label, String.t()
      attribute :type, String.t()

      embeds_many :options, Option, default: [] do
        attribute :label, String.t()
        attribute :value, String.t()
      end
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions