Firebase 事务方法是否与所有写入操作(包括云函数的写入操作)兼容?



我知道Transactions是如何工作的,因为它自动执行操作并防止用户之间的竞争但我的问题是,这是否适用于任何在Firestore上编写的操作,无论是来自用户还是来自云功能?

<步骤/strong>

1——下面是云函数操作,它将firststore (boolen value)写入isAcar field, docUID为123,在下面的代码中,我不关心任何条件,写

exports.onUserStatusChanged = functions.database.ref('/users/{uid}').onUpdate(
async (change, context) => {
const eventStatus = change.after.val();
const userStatusFirestoreRef = firestore.doc(`users/${context.params.uid}`);
return userStatusFirestoreRef.update(eventStatus);
});

2-以下是在应用程序客户端

myFunction(){
DocumentReference doc = FirebaseFirestore.instance.collection("users").doc('123');
FirebaseFirestore.instance.runTransaction((transaction) async {
DocumentSnapshot docVal = await transaction.get(doc );
if (docVal.get('isAcar ')==false) {
transaction.update(doc ,{
'isAcar ':true, 
});
}
});
} 

第二个代码中的写操作是原子的吗?或者我还必须在云函数中使用横切写操作

是的,您可以使用来自客户端或来自Cloud Functions的事务。

最新更新