diff --git a/candishared/database_update_tools.go b/candishared/database_update_tools.go index dbe433a..3ff56d9 100644 --- a/candishared/database_update_tools.go +++ b/candishared/database_update_tools.go @@ -84,6 +84,7 @@ type DBUpdateTools struct { KeyExtractorFunc func(structTag reflect.StructField) (res DBUpdateOptionKeyExtractorResult) FieldValueExtractor func(reflect.Value) (val any, skip bool) IgnoredFields []string + UpdatedFields []string } func (d *DBUpdateTools) parseOption(opts ...DBUpdateOptionFunc) (o partialUpdateOption) { @@ -101,7 +102,12 @@ func (d DBUpdateTools) ToMap(data any, opts ...DBUpdateOptionFunc) map[string]an dataType := candihelper.ReflectTypeUnwrapPtr(reflect.TypeOf(data)) isPartial := len(opt.updateFields) > 0 || len(opt.ignoreFields) > 0 - updateFields := make(map[string]any, 0) + defaultUpdatedFields := make(map[string]bool) + for _, fieldName := range d.UpdatedFields { + defaultUpdatedFields[fieldName] = true + } + + updateFields := make(map[string]any) for i := 0; i < dataValue.NumField(); i++ { fieldValue := candihelper.ReflectValueUnwrapPtr(dataValue.Field(i)) fieldType := dataType.Field(i) @@ -167,6 +173,10 @@ func (d DBUpdateTools) ToMap(data any, opts ...DBUpdateOptionFunc) map[string]an if (isFieldUpdated && len(opt.updateFields) > 0) || (!isFieldIgnored && len(opt.ignoreFields) > 0) { updateFields[key] = val } + + if ok := defaultUpdatedFields[key]; ok { + updateFields[key] = val + } } for _, ignored := range d.IgnoredFields { diff --git a/candishared/database_update_tools_test.go b/candishared/database_update_tools_test.go index 6097b43..9031a64 100644 --- a/candishared/database_update_tools_test.go +++ b/candishared/database_update_tools_test.go @@ -188,3 +188,37 @@ func TestDBUpdateSqlExtractorKey(t *testing.T) { assert.Equal(t, "{\"1\",\"2\",\"3\"}", updated["str_arr"]) assert.Equal(t, []byte(`123`), updated["log"]) } + +func TestDBUpdateToolsMongoUpdatedField(t *testing.T) { + type SubModel struct { + Title string `bson:"title" json:"title"` + Profile string `bson:"profile" json:"profile"` + CityAddress string `bson:"city_address"` + } + type Model struct { + ID int `bson:"db_id" json:"id"` + Name *string `bson:"db_name" json:"name"` + Address string `bson:"db_address" json:"address"` + Rel SubModel `bson:"rel" json:"rel"` + SubModel + } + + updated := DBUpdateTools{ + KeyExtractorFunc: DBUpdateMongoExtractorKey, + UpdatedFields: []string{"db_address"}, + }.ToMap( + &Model{ + ID: 1, + Name: candihelper.WrapPtr("01"), + Address: "Indonesia", + SubModel: SubModel{Title: "test", CityAddress: "Jakarta"}, + Rel: SubModel{Title: "rel sub"}}, + DBUpdateSetUpdatedFields("ID", "Name", "Title"), + ) + + assert.Equal(t, 4, len(updated)) + assert.Equal(t, 1, updated["db_id"]) + assert.Equal(t, "01", updated["db_name"]) + assert.Equal(t, "test", updated["title"]) + assert.Equal(t, "Indonesia", updated["db_address"]) +}