Skip to content

Proper way of populating the nested objects default fields #39

Answered by mehran-prs
wojciechbator asked this question in Q&A
Discussion options

You must be logged in to vote

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 the primitive.NewObjectID() to generate a new ID for you.

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 so…

Replies: 3 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@wojciechbator
Comment options

@mehran-prs
Comment options

Answer selected by mehran-prs
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants