Skip to content

Transactions

Goose provides an elegant wrapper around MongoDB transactions via client.WithTransaction.

Executing a Transaction

You can pass a callback function to WithTransaction. If the callback returns an error, the transaction is automatically aborted. If it returns nil, the transaction is committed.

err := goose.WithTransaction(ctx, func(sessCtx mongo.SessionContext) error {
    user := &User{Name: "Alice"}
    if err := UserModel.Save(sessCtx, user); err != nil {
        return err
    }

    log := &Log{Message: "User created"}
    if err := LogModel.Save(sessCtx, log); err != nil {
        return err // Transaction will abort
    }

    return nil
})

if err != nil {
    log.Printf("Transaction failed: %v", err)
}

Replica Sets

MongoDB transactions require a replica set. Make sure your MongoDB deployment supports transactions before using them.