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.