You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: lib/mongo/collection.ex
+136-1Lines changed: 136 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -278,7 +278,7 @@ defmodule Mongo.Collection do
278
278
279
279
defmodule Board do
280
280
281
-
use Collection
281
+
use Collection
282
282
283
283
collection "boards" do
284
284
@@ -358,6 +358,94 @@ defmodule Mongo.Collection do
358
358
"modified" : ISODate("2020-05-19T15:15:14.374Z"),
359
359
"title" : "Vega"
360
360
}
361
+
## Example `timestamps`
362
+
363
+
defmodule Post do
364
+
365
+
use Mongo.Collection
366
+
367
+
collection "posts" do
368
+
attribute :title, String.t()
369
+
timestamps()
370
+
end
371
+
372
+
def new(title) do
373
+
Map.put(new(), :title, title)
374
+
end
375
+
376
+
def store(post) do
377
+
MyRepo.insert_or_update(post)
378
+
end
379
+
end
380
+
381
+
In this example the macro `timestamps` is used to create two DateTime attributes, `inserted_at` and `updated_at`.
382
+
This macro is intented to use with the Repo module, as it will be responsible for updating the value of `updated_at` attribute before execute the action.
383
+
384
+
iex(1)> post = Post.new("lorem ipsum dolor sit amet")
385
+
%Post{
386
+
_id: #BSON.ObjectId<6327a7099626f7f61607e179>,
387
+
inserted_at: ~U[2022-09-18 23:17:29.087092Z],
388
+
title: "lorem ipsum dolor sit amet",
389
+
updated_at: ~U[2022-09-18 23:17:29.087070Z]
390
+
}
391
+
392
+
iex(2)> Post.store(post)
393
+
{:ok,
394
+
%{
395
+
_id: #BSON.ObjectId<6327a7099626f7f61607e179>,
396
+
inserted_at: ~U[2022-09-18 23:17:29.087092Z],
397
+
title: "lorem ipsum dolor sit amet",
398
+
updated_at: ~U[2022-09-18 23:19:24.516648Z]
399
+
}}
400
+
401
+
Is possible to change the field names, like Ecto does, and also change the default behaviour:
The `timestamps` macro has some limitations as it does not run in batch commands like `insert_all` or `update_all`, nor does it update embedded documents.
0 commit comments