Skip to content

Automatically update fields

jiangz222 edited this page Nov 26, 2020 · 11 revisions

Qmgo support two ways to make specific fields automatically update in specific API, check examples here:

Default fields

  • Inject field.DefaultField in document struct, Qmgo will update createAtupdateAt and _id in update and insert operation.
type User struct {
    field.DefaultField `bson:",inline"`
    Name string `bson:"name"`
    Age  int    `bson:"age"`
}
u := &User{Name: "Lucas", Age: 7}
_, err := cli.InsertOne(context.Background(), u)
// Fields with tag createAt、updateAt and _id will be generated automatically 
  • Support fields:
Field Supported type Supported API
CreateAt time.Time InsertOne / InsertMany / Upsert / UpdateId / UpsertId
UpdateAt time.Time InsertOne / InsertMany / Upsert / ReplaceOne / UpdateId / UpsertId
Id primitive.ObjectID InsertOne / InsertMany / Upsert / UpdateId / UpsertId

Note: To field Id and API Upsert,if replacement document in Upsert has "_id" field and the document exists, please initial it with existing id.

Custom fields

  • The document *struct has to implement:

CustomFields() field.CustomFieldsBuilder

  • Define the custom fields, Qmgo will update them in update and insert operation.
type User struct {
    Name string `bson:"name"`
    Age  int    `bson:"age"`

    MyId         string    `bson:"myId"`
    CreateTimeAt time.Time `bson:"createTimeAt"`
    UpdateTimeAt int64     `bson:"updateTimeAt"`
}

// Implement CustomFields() field.CustomFieldsBuilder 
// And define the custom fields
func (u *User) CustomFields() field.CustomFieldsBuilder {
    return field.NewCustom().SetCreateAt("CreateTimeAt").SetUpdateAt("UpdateTimeAt").SetId("MyId")
}

u := &User{Name: "Lucas", Age: 7}
_, err := cli.InsertOne(context.Background(), u)
// CreateTimeAt、UpdateTimeAt and MyId will be generated automatically 
  
// suppose Id and ui is ready
err = cli.ReplaceOne(context.Background(), bson.M{"_id": Id}, &ui)
// UpdateTimeAt will update
  • Supported fields
Field Supported type Supported API
Custom createAt filed time.Time / int64(unix timestamp) InsertOne / InsertMany / Upsert / UpdateId / UpsertId
Custom updateAt field time.Time / int64(unix timestamp) InsertOne / InsertMany / Upsert / ReplaceOne
Custom Id field primitive.ObjectID/string InsertOne / InsertMany / Upsert / UpdateId / UpsertId

Note:To field Custom Id and API Upsert,if replacement document in Upsert has "_id" field and the document exists, please initial it with existing id.

Clone this wiki locally