如果任何写入操作失败,如何中止FireStore事务?

时间:2018-09-21 19:18:26

标签: node.js firebase transactions google-cloud-firestore

在下面的代码中,我正在更新事务中的两个文档。但是,如果仅更新之一成功而另一更新由于某种原因失败,则FireStore仍将完成事务。如果任何写入操作失败,如何中止事务?

var country; // forget to set a value to this variable
// Create a reference to the SF doc.
var sfDocRef = db.collection("cities").doc("SF");
var usaDocRef = db.collection("country").doc(country);  //country is undefined  
db.runTransaction(function(transaction) {
    return transaction.get(sfDocRef).then(function(sfDoc) {
        if (!sfDoc.exists) {
            throw "Document does not exist!";
        }

        var newPopulation = sfDoc.data().population + 1;
        if (newPopulation <= 1000000) {
            transaction.update(sfDocRef, { population: newPopulation }); //Will succeed
            transaction.update(usaDocRef, { lastPopulationUpdate: new Date()}); //Will fail
            return newPopulation;
        } else {
            return Promise.reject("Sorry! Population is too big.");
        }
    });
}).then(function(newPopulation) {
    console.log("Population increased to ", newPopulation);
}).catch(function(err) {
    // This will be an "population is too big" error.
    console.error(err);
});

在上面的示例中,我们忘记为country分配值。

0 个答案:

没有答案