diff --git a/mdb/collection.go b/mdb/collection.go index 3a15fb1..57970a8 100644 --- a/mdb/collection.go +++ b/mdb/collection.go @@ -237,6 +237,27 @@ func (c *Collection[T]) update(tx *Snapshot, userItem *T) error { return nil } +func (c *Collection[T]) UpdateFunc(tx *Snapshot, id uint64, update func(item *T) error) error { + if tx == nil { + return c.db.Update(func(tx *Snapshot) error { + return c.updateFunc(tx, id, update) + }) + } + return c.updateFunc(tx, id, update) +} + +func (c *Collection[T]) updateFunc(tx *Snapshot, id uint64, update func(item *T) error) error { + item := c.Get(tx, id) + if item == nil { + return errs.NotFound + } + if err := update(item); err != nil { + return err + } + c.setID(item, id) // Don't allow the ID to change. + return c.update(tx, item) +} + func (c *Collection[T]) Upsert(tx *Snapshot, item *T) error { if tx == nil { return c.db.Update(func(tx *Snapshot) error {