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

I use the MongoDB transaction in go-zero as follows,it's useless when rollback,who can answer me? #4000

Open
pigfu opened this issue Mar 12, 2024 · 1 comment

Comments

@pigfu
Copy link

pigfu commented Mar 12, 2024

       sess, err := m.conn.StartSession()
	if err != nil {
		return err
	}
	defer sess.EndSession(ctx)
	err = sess.StartTransaction()
	if err != nil {
		return err
	}
	ctx = mongo.NewSessionContext(ctx, sess)
	defer func() {
		if err != nil {
			_ = sess.AbortTransaction(ctx)
		}
	}()
       for _, item := range data {
		_, err = m.conn.Collection.InsertOne(ctx, item)
		if err != nil {
			return err
		}
	}
	_ = sess.CommitTransaction(ctx)
	return nil

but as follows,it's useful !!!!!!!!!!!!!!!

        sess, err := m.conn.StartSession()
	if err != nil {
		return err
	}
	defer sess.EndSession(ctx)
        _, err = sess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		defer func() {
			if err != nil {
				_ = sessCtx.AbortTransaction(ctx)
			}
		}()
		for _, item := range data {
			_, err = m.conn.Collection.InsertOne(sessCtx, item)
			if err != nil {
				return nil, err
			}
		}
		err = sessCtx.CommitTransaction(sessCtx)
		return nil, err
	})
	if err != nil {
		return err
	}
@kevwan
Copy link
Contributor

kevwan commented Mar 30, 2024

Didn't get what's the problem?

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