Firestore交易:部分成功问题

时间:2018-09-22 13:48:11

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

在下面的代码中,FireStore部分成功。这意味着并非所有的写操作都成功,但有些成功。 请运行它,然后自己看看。

错误原因是foo.bar foo未定义。如何告诉FireStore如果发生任何错误,则中止一切?

testTransaction(){
        var country = 'USA';
        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!";
                }
                // console.log(sadf.t)
                var newPopulation = sfDoc.data().population + 1;
                if (newPopulation <= 10000000) {
                    transaction.set(sfDocRef, { population: newPopulation }, {merge:true}); //Will succeed
                    console.log(foo.bar) //ERROR is here
                    transaction.update(usaDocRef, { lastPopulationUpdate: new Date()}); //Will fail
                    return newPopulation;
                } else {
                    return Promise.reject("Sorry! Population is too big.");
                }
            }).catch(e => {
                console.log(e)

            })
        }).then(function(newPopulation) {
            console.log("Population increased to ", newPopulation);
        }).catch(function(err) {
            // This will be an "population is too big" error.
            console.error(err);
        });
    }

要生成测试数据,请使用以下方法:

   addDummy(){
        // Get a new write batch
        var batch = db.batch();
        var sfRef = db.collection("cities").doc("SF");
        batch.set(sfRef, {"population": 1000000});
        var laRef = db.collection("country").doc("USA");
        batch.set(laRef, {"name": 'United States of America'})
        batch.commit().then(function () {
        });
    }

0 个答案:

没有答案