Skip to content

safe concurrent update #79

Open
Open
@antoniomralmeida

Description

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()
}
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions