Whats is the best way of working with embedded structs in ecto and mongodb

we are working here with ecto in combination with a mongodb. but we are not using any mongodb adapter, but are working directly with the mongo driver.

but we do use ecto for validations. this worked without a problem as long as we do not had any embedded objects. but now we are getting “problems” (not very nice code) when using with embedded objects.

as long, as we do not had any embedded object, we simply could use “changeset.changes” to get the data we want to save.

If I use embeds_many as in

changeset = Ecto.Changeset.put_embed(changeset, :items, items)

from https://hexdocs.pm/ecto/Ecto.Schema.html#embeds_many/3, I do not only get the data to save in changeset.changes, but also included sub changesets.

is there a way the simply get the data to save?

actually the changeset looks like:

changes: %{children: [#Ecto.Changeset<action: :insert,
changes: %{name: “abc”, age: 12}, errors: [],
data: #Children<>, valid?: true>,
#Ecto.Changeset<action: :insert, changes: %{age: 17, name: “cde”},
errors: [], data: #Children<>, valid?: true>]},
errors: [], data: #Parent<>, valid?: true>

I would like to have:

changes: %{children: %{name: “abc”, age: 12}, %{age: 17, name: “cde”}}

do I have to manually transform the data or is there any function that does this for me?

the definition looks like:

schema “parent” do
embeds_many :children Children
end

embedded_schema do
field :name, :string
field :age, :integer
end

1 Like

I’m facing same problem now. Is there is any existed function or manual function in elixir for getting the changes with embeded changes.