Heim  >  Artikel  >  Backend-Entwicklung  >  MongoDB-Transaktion, Callback-API-Methode

MongoDB-Transaktion, Callback-API-Methode

WBOY
WBOYnach vorne
2024-02-06 09:35:03678Durchsuche

MongoDB 事务,回调 API 方式

Frageninhalt

Nachdem ich viele Dokumente/Artikel über MongoDB-Transaktionen gelesen habe, benötige ich noch weitere Erläuterungen.

Hier heißt es:

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.

Aber es werden weiterhin die Kern-API-Methoden vorgestellt, ohne die empfohlenen Methoden überhaupt zu berühren.

Die offizielle Dokumentation hier sagt:

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)

Aber wenn es um den alles entscheidenden Schritt „Angegebene Aktion ausführen“ geht, zeigt das Beispiel keinen relevanten Code. Das heißt, ich „brauche noch ein echtes Beispiel“, wie in MongoDB Transactions In NodeJS gefragt.

PS. Für den Fall, dass sich die Beispiele ändern oder verschwinden, finden Sie hier die Golang-Version:
// 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
}

Aus dem Beispiel geht hervor, dass der wichtigste Schritt „Angegebene Aktion ausführen“ im Rückruf erfolgt. ist das so? Wenn ja, muss dies in der offiziellen Dokumentation unbedingt hervorgehoben werden.


Richtige Antwort


Beispiel abgeschlossen. Es enthält die folgenden Kernkommentare:

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

Alsocallback函数是由Session执行的.WithTransaction() Methode. Sie rufen die callback 函数传递给它,它将被 Session.WithTransaction()-Methode auf.

Diese Implementierung stellt sicher, dass in der Rückruffunktion abgeschlossene Vorgänge als Transaktion ausgeführt werden (d. h. entweder alle Vorgänge werden angewendet oder es werden keine Vorgänge angewendet). Wenn die Rückruffunktion einen Nicht-nil-Fehler zurückgibt, wird die Transaktion abgebrochen, andernfalls wird die Transaktion festgeschrieben.

Das obige ist der detaillierte Inhalt vonMongoDB-Transaktion, Callback-API-Methode. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:stackoverflow.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen