MongoDB transaction, callback API method

WBOY
Release: 2024-02-06 09:35:03
forward
717 people have browsed it

MongoDB 事务,回调 API 方式

Question content

After reading many documents/articles about MongoDB transactions, I still need further clarification.

Here it says:

MongoDB provides two APIs to use transactions. The first is the core API which has similar syntax to relational databases. The second, the callback API, is the recommended approach to using transactions in MongoDB.
Copy after login

But it goes on to introduce the core API methods without touching the recommended methods at all.

The official documentation here says,

This example highlights the key components of the transactions API. In particular, it uses the callback API. The callback API:

starts a transaction
executes the specified operations
commits the result (or aborts on error)

Copy after login

But when it comes to the all-important "perform the specified action" step, the example doesn't show any relevant code. That is, I "still need a real example" as asked in MongoDB Transactions In NodeJS.

PS. In case the examples change or disappear, here are the Golang versions:

// WithTransactionExample is an example of using the Session.WithTransaction function.
func WithTransactionExample(ctx context.Context) error {
    // For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
    // uri := "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl"
    // For a sharded cluster, connect to the mongos instances; e.g.
    // uri := "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/"
    uri := mtest.ClusterURI()
    clientOpts := options.Client().ApplyURI(uri)
    client, err := mongo.Connect(ctx, clientOpts)
    if err != nil {
        return err
    }
    defer func() { _ = client.Disconnect(ctx) }()
    // Prereq: Create collections.
    wcMajority := writeconcern.Majority()
    wcMajority.WTimeout = 1 * time.Second
    wcMajorityCollectionOpts := options.Collection().SetWriteConcern(wcMajority)
    fooColl := client.Database("mydb1").Collection("foo", wcMajorityCollectionOpts)
    barColl := client.Database("mydb1").Collection("bar", wcMajorityCollectionOpts)
    // Step 1: Define the callback that specifies the sequence of operations to perform inside the transaction.
    callback := func(sessCtx mongo.SessionContext) (interface{}, error) {
        // Important: You must pass sessCtx as the Context parameter to the operations for them to be executed in the
        // transaction.
        if _, err := fooColl.InsertOne(sessCtx, bson.D{{"abc", 1}}); err != nil {
            return nil, err
        }
        if _, err := barColl.InsertOne(sessCtx, bson.D{{"xyz", 999}}); err != nil {
            return nil, err
        }
        return nil, nil
    }
    // Step 2: Start a session and run the callback using WithTransaction.
    session, err := client.StartSession()
    if err != nil {
        return err
    }
    defer session.EndSession(ctx)
    result, err := session.WithTransaction(ctx, callback)
    if err != nil {
        return err
    }
    log.Printf("result: %v\n", result)
    return nil
}
Copy after login

It seems to me from the example that the most important "perform the specified action" step is done in the callback. is that so? If so, the official documentation really needs to emphasize this.


Correct answer


Example completed. It contains the following key comments:

// Step 2: Start a session and run the callback using WithTransaction.
Copy after login

So the callback function is executed by Session.WithTransaction() method. You pass it the callback function and it will be called by the Session.WithTransaction() method.

This implementation ensures that operations completed in the callback function will be performed as a transaction (i.e., either all operations are applied or no operations are applied). If the callback function returns a non-nil error, the transaction will be aborted, otherwise the transaction will be committed.

The above is the detailed content of MongoDB transaction, callback API method. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template