Proper way of populating the nested objects default fields #39
-
Hi! I use this library as an ODM in my project. I have an issue however with populating nested objects default model fields, like _id, created_at and updated_at. I persist the object using To visualize it a bit better:
and saving: results in |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Hi @wojciechbator, This is what our default mgm model's hooks do: // Creating hook is used here to set the `created_at` field
// value when inserting a new model into the database.
func (f *DateFields) Creating() error {
f.CreatedAt = time.Now().UTC()
return nil
}
// Saving hook is used here to set the `updated_at` field
// value when creating or updateing a model.
func (f *DateFields) Saving() error {
f.UpdatedAt = time.Now().UTC()
return nil
} You can change your root model's hooks to something like this: type Player struct {
mgm.DefaultModel
// other fields...
}
type Team struct {
mgm.DefaultModel
Players []Player
// other fields...
}
// Creating called when creating a new model.
func (t *Team) Creating() error {
now := time.Now().UTC()
t.CreatedAt = now
for _, p := range t.Players {
p.ID = primitive.NewObjectID()
p.CreatedAt = now
}
return nil
}
// Saving when creating or updating a model.
func (t *Team) Saving() error {
now:=time.Now().UTC()
t.UpdatedAt = now
for _, p := range t.Players {
p.UpdatedAt = now
}
return nil
} |
Beta Was this translation helpful? Give feedback.
-
How about adding an embeded document model? something similar to |
Beta Was this translation helpful? Give feedback.
-
Hi @amirhossein-shakeri-work |
Beta Was this translation helpful? Give feedback.
Hi @wojciechbator,
Yes, that's because
Create
only supports the first level, For nested levels, you need to use custom hooks.For
_id
you can just simply use theprimitive.NewObjectID()
to generate a new ID for you.This is what our default mgm model's hooks do:
You can change your root model's hooks to so…