Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

safe concurrent update #79

Open
antoniomralmeida opened this issue Jan 20, 2023 · 1 comment
Open

safe concurrent update #79

antoniomralmeida opened this issue Jan 20, 2023 · 1 comment
Assignees

Comments

@antoniomralmeida
Copy link

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

@mehran-prs
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants