Skip to content

Commit c1b60b4

Browse files
committed
fix: remove derived attributes in the dump function
1 parent e7f2d44 commit c1b60b4

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

lib/mongo/collection.ex

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -689,11 +689,13 @@ defmodule Mongo.Collection do
689689
quote unquote: false do
690690
attrs_mapping =
691691
@attributes
692+
|> Enum.reject(fn {name, _opts} -> Enum.member?(@derived, name) end)
692693
|> Enum.map(fn {name, opts} -> {name, opts[:name]} end)
693694
|> Enum.map(fn {name, {_, src_name}} -> {name, src_name} end)
694695

695696
embeds_mapping =
696697
(@embed_ones ++ @embed_manys)
698+
|> Enum.reject(fn {name, _mod, _opts} -> Enum.member?(@derived, name) end)
697699
|> Enum.filter(fn {_name, mod, _opts} -> Collection.has_load_function?(mod) end)
698700
|> Enum.map(fn {name, mod, opts} -> {name, mod, opts[:name]} end)
699701
|> Enum.map(fn {name, mod, {_, src_name}} -> {mod, name, src_name} end)

test/collections/simple_test.exs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,33 @@ defmodule Collections.SimpleTest do
1212
{:ok, [pid: pid]}
1313
end
1414

15+
defmodule Task do
16+
use Collection
17+
18+
collection "tasks" do
19+
attribute :name, String.t(), default: "Fix errors"
20+
attribute :status, integer(), derived: true
21+
after_load &Task.after_load/1
22+
end
23+
24+
def after_load(task) do
25+
%Task{task | status: :loaded}
26+
end
27+
28+
def insert_one(task, top) do
29+
with map <- dump(task),
30+
{:ok, _} <- Mongo.insert_one(top, @collection, map) do
31+
:ok
32+
end
33+
end
34+
35+
def find_one(id, top) do
36+
top
37+
|> Mongo.find_one(@collection, %{@id => id})
38+
|> load()
39+
end
40+
end
41+
1542
defmodule Label do
1643
use Collection
1744

@@ -89,6 +116,21 @@ defmodule Collections.SimpleTest do
89116
assert %Card{intro: "new intro", label: %Label{color: :red, name: "warning"}} = struct_card
90117
end
91118

119+
test "dump derived attributes", c do
120+
alias Collections.SimpleTest.Task
121+
task = %Task{Task.new() | status: :red}
122+
assert Map.has_key?(Task.dump(task), "status") == false
123+
124+
assert :ok = Task.insert_one(task, c.pid)
125+
126+
task = Task.find_one(task._id, c.pid)
127+
128+
assert %Task{status: :loaded} = task
129+
130+
task = Mongo.find_one(c.pid, "tasks", %{_id: task._id})
131+
assert Map.has_key?(task, "status") == false
132+
end
133+
92134
test "save and find", c do
93135
alias Collections.SimpleTest.Card
94136
alias Collections.SimpleTest.Label

0 commit comments

Comments
 (0)