- 
                Notifications
    
You must be signed in to change notification settings  - Fork 152
 
Automatically update fields
        jiangz222 edited this page Sep 19, 2020 
        ·
        11 revisions
      
    Qmgo support two ways to make specific fields automatically update in specific API, check examples here:
- Inject 
field.DefaultFieldin document struct, Qmgo will updatecreateAt、updateAtand_idin 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 | support type | support API | 
|---|---|---|
| CreateAt | time.Time | InsertOne / InsertMany/Upsert | 
| UpdateAt | time.Time | InsertOne / InsertMany/Upsert/UpdateWithDocument | 
| Id | primitive.ObjectID | InsertOne / InsertMany/Upser | 
- 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.UpdateWithDocument(context.Background(), bson.M{"_id": Id}, &ui)
// UpdateTimeAt will update- Supported fields
 
| Field | support type | support API | 
|---|---|---|
| Custom createAt filed | time.Time / int64(unix timestamp) | InsertOne / InsertMany / Upsert | 
| Custom updateAt field | time.Time / int64(unix timestamp) | InsertOne / InsertMany / UpdateWithDocument | 
| Custom Id field | primitive.ObjectID/string | InsertOne / InsertMany / Upsert |