Kamva/mgm

safe concurrent update

antoniomralmeida opened this issue · 1 comments

A safe concurrent update mode is to take advantage of the last change date attribute and check before the update if the document remains the same, if not the document has been changed by someone else and the update cannot be done.

//model.go
type Model interface {
// PrepareID converts the id value if needed, then
// returns it (e.g convert string to objectId).
PrepareID(id interface{}) (interface{}, error)

GetID() interface{}
SetID(id interface{})
GetPrimitiveUpdateAt() primitive.DateTime

}

//field.go
func (f *DateFields) GetPrimitiveUpdateAt() primitive.DateTime {
return primitive.NewDateTimeFromTime(f.UpdatedAt)
}

///collection.go

func (coll *Collection) SecureConcurrentUpdate(model Model, opts ...*options.UpdateOptions) error {
res := mgm.Coll(model).FindOne(mgm.Ctx(), bson.D{{"_id", model.GetID()}, {"updated_at", model.GetPrimitiveUpdateAt()}})
if res.Err() == nil {
return mgm.Coll(model).Update(model, opts...)
} else {
return res.Err()
}
}

Hi @antoniomralmeida
Unfortunately, we do not support this feature right now, but maybe later implement it.
PRs are welcome.