mongotx

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2020 License: Apache-2.0 Imports: 3 Imported by: 0

README

exa-bit/pkg/mongo-tx

Contains simplified closure based function to create multi documents transaction. The aim is to provide similar function signature to work with mongo transaction as with another database (ie. sql and pgx).

Tested On

  • mongodb v4.2 - go.mongodb.org/mongo-driver v1.4.0-rc0

Documentation

Overview

Package mongotx contains simplified closure based function to create multi documents transaction.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MongoInTransaction

func MongoInTransaction(ctx context.Context, db *mongo.Database, fn func(sc context.Context) error, opts ...*options.TransactionOptions) error

MongoInTransaction creates and starts a new Session and use it to call the fn callback. The Context try be used as the Context parameter for any operations in the fn callback that should be executed under the session. If the ctx parameter already contains a Session, that Session will be reused instead effectively become 1 transaction. To create new transaction instead of reused transaction, supply different ctx which doesn't contains any `mongo.Session`. Any error returned by the fn callback will abort (rollback) the transaction, otherwise commit it. An error will be returned if there is error when performing commit or abort operation.

Example
var db *mongo.Database // assume db is valid

err := mongotx.MongoInTransaction(context.TODO(), db, func(sc context.Context) error {
	res, err := db.Collection("posts").InsertOne(sc, bson.M{"title": "My post"})
	if err != nil {
		return err
	}
	postId := res.InsertedID.(primitive.ObjectID)
	res, err = db.Collection("comments").InsertOne(sc, bson.M{"review": "My review", "post_id": postId})
	if err != nil {
		return err // return err will rollback transaction
	}
	return nil // return nil (no error) will commit transaction
})
log.Fatal("cannot start transaction!", err)
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL