Firebase Firestore-在一个事务中执行多个添加和更新操作

Firebase Firestore-在一个事务中执行多个添加和更新操作,firebase,transactions,google-cloud-firestore,google-cloud-functions,Firebase,Transactions,Google Cloud Firestore,Google Cloud Functions,我有一个Firestore文档,表示一天,其中包含Firestore数据库中当天的预订的子集合 以下是我的数据结构的JSON示例: { "Day":{ "ReservationsCount":2, "Reservations":[ { "Order":1 }, { "Order":2 } ] } } 我需要添

我有一个Firestore文档,表示一天,其中包含Firestore数据库中当天的预订的子集合

以下是我的数据结构的JSON示例:

{  
   "Day":{  
      "ReservationsCount":2,
      "Reservations":[  
         {  
            "Order":1
         },
         {  
            "Order":2
         }
      ]
   }
}
我需要添加一组文档,在集合中设置它们的序号,并在一个事务中更新ReservationScont

我尝试使用firestore事务和批处理写入,但据我所知,它们不支持在事务中向集合添加文档(仅根据set()、update()或delete()操作的组合)

我试着用云函数更新这些值,但它们是beta版的,所以有时我会得到错误的结果


是否有任何方法可以在一个事务中更新现有文档并将文档添加到其子集合?

以下操作可以完成。您必须将“day”文档的ref、子集合的ref和一个数组传递给
updateRes()
函数,该数组包含要添加到子集合的每个文档的对象

只需在浏览器中打开HTML文件

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-firestore.js"></script>
</head>

<body>

    <script>

        var config = {
            apiKey: "...",
            authDomain: "...",
            databaseURL: "...",
            ....
        };

        firebase.initializeApp(config);

        var firestoredb = firebase.firestore();


        function updateRes(dayDocRef, orderCollectionRef, refAndDataArray) {

            return firestoredb.runTransaction(function (transaction) {

                return transaction.get(dayDocRef)
                    .then(function (dayDoc) {

                        if (!dayDoc.exists) {
                            throw "Document Day does not exist!";
                        }

                        newResCount = dayDoc.data().ReservationsCount + refAndDataArray.length;

                        return transaction.update(dayDocRef, { ReservationsCount: newResCount });

                    })
                    .then(function () {

                        var t = transaction;

                        refAndDataArray.forEach(function (element) {
                            t = t.set(orderCollectionRef.doc(element.ref), element.data);
                        });

                        return t;

                    });

            }).then(function () {
                console.log("Transaction successfully committed!");
            }).catch(function (error) {
                console.log("Transaction failed: ", error);
            });

        };


        var dayDocRef = firestoredb.collection("Days").doc("Day");
        var orderCollectionRef = dayDocRef.collection("Reservations"); //The sub-collection is called "Reservations"

        var refAndDataArray = [{ ref: "3", data: { Order: 3, otherData: "foo" } }, { ref: "4", data: { Order: 4, otherData: "bar" } }];

        updateRes(dayDocRef, orderCollectionRef, refAndDataArray);


    </script>


</body>

</html>

变量配置={
apiKey:“…”,
authDomain:“…”,
数据库URL:“…”,
....
};
firebase.initializeApp(配置);
var firestoredb=firebase.firestore();
函数更新(dayDocRef、orderCollectionRef、refAndDataArray){
返回firestoredb.runTransaction(函数(事务){
返回事务.get(dayDocRef)
.then(函数(dayDoc){
如果(!dayDoc.存在){
抛出“文档日不存在!”;
}
newResCount=dayDoc.data().ReservationsCount+refAndDataArray.length;
return transaction.update(dayDocRef,{reservationscont:newResCount});
})
.然后(函数(){
var t=交易;
refAndDataArray.forEach(函数(元素){
t=t.set(orderCollectionRef.doc(element.ref)、element.data);
});
返回t;
});
}).然后(函数(){
log(“事务已成功提交!”);
}).catch(函数(错误){
日志(“事务失败:”,错误);
});
};
var dayDocRef=firestoredb.collection(“天”).doc(“天”);
var orderCollectionRef=dayDocRef.collection(“保留”);//子集合称为“保留”
var refAndDataArray=[{ref:“3”,数据:{Order:3,otherData:“foo”},{ref:“4”,数据:{Order:4,otherData:“bar”}];
更新(dayDocRef、orderCollectionRef、refAndDataArray);

以下操作应该可以完成。您必须将“day”文档的ref、子集合的ref和一个数组传递给
updateRes()
函数,该数组包含要添加到子集合的每个文档的对象

只需在浏览器中打开HTML文件

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-firestore.js"></script>
</head>

<body>

    <script>

        var config = {
            apiKey: "...",
            authDomain: "...",
            databaseURL: "...",
            ....
        };

        firebase.initializeApp(config);

        var firestoredb = firebase.firestore();


        function updateRes(dayDocRef, orderCollectionRef, refAndDataArray) {

            return firestoredb.runTransaction(function (transaction) {

                return transaction.get(dayDocRef)
                    .then(function (dayDoc) {

                        if (!dayDoc.exists) {
                            throw "Document Day does not exist!";
                        }

                        newResCount = dayDoc.data().ReservationsCount + refAndDataArray.length;

                        return transaction.update(dayDocRef, { ReservationsCount: newResCount });

                    })
                    .then(function () {

                        var t = transaction;

                        refAndDataArray.forEach(function (element) {
                            t = t.set(orderCollectionRef.doc(element.ref), element.data);
                        });

                        return t;

                    });

            }).then(function () {
                console.log("Transaction successfully committed!");
            }).catch(function (error) {
                console.log("Transaction failed: ", error);
            });

        };


        var dayDocRef = firestoredb.collection("Days").doc("Day");
        var orderCollectionRef = dayDocRef.collection("Reservations"); //The sub-collection is called "Reservations"

        var refAndDataArray = [{ ref: "3", data: { Order: 3, otherData: "foo" } }, { ref: "4", data: { Order: 4, otherData: "bar" } }];

        updateRes(dayDocRef, orderCollectionRef, refAndDataArray);


    </script>


</body>

</html>

变量配置={
apiKey:“…”,
authDomain:“…”,
数据库URL:“…”,
....
};
firebase.initializeApp(配置);
var firestoredb=firebase.firestore();
函数更新(dayDocRef、orderCollectionRef、refAndDataArray){
返回firestoredb.runTransaction(函数(事务){
返回事务.get(dayDocRef)
.then(函数(dayDoc){
如果(!dayDoc.存在){
抛出“文档日不存在!”;
}
newResCount=dayDoc.data().ReservationsCount+refAndDataArray.length;
return transaction.update(dayDocRef,{reservationscont:newResCount});
})
.然后(函数(){
var t=交易;
refAndDataArray.forEach(函数(元素){
t=t.set(orderCollectionRef.doc(element.ref)、element.data);
});
返回t;
});
}).然后(函数(){
log(“事务已成功提交!”);
}).catch(函数(错误){
日志(“事务失败:”,错误);
});
};
var dayDocRef=firestoredb.collection(“天”).doc(“天”);
var orderCollectionRef=dayDocRef.collection(“保留”)//子集合称为“预订”
var refAndDataArray=[{ref:“3”,数据:{Order:3,otherData:“foo”},{ref:“4”,数据:{Order:4,otherData:“bar”}];
更新(dayDocRef、orderCollectionRef、refAndDataArray);
set()和
update()
操作都可以创建文档。如果您在执行此操作时遇到问题,请共享。
set()
update()
操作都可以创建文档。如果您在实现此功能时遇到问题,请与他人分享。