gpt4 book ai didi

javascript - 在 firebase 中同时更新数组

转载 作者:行者123 更新时间:2023-11-30 14:15:44 26 4
gpt4 key购买 nike

.runTransaction(async transaction => {
const newContractUid = uuid();
const newContractRef = firestore
.collection(COLLECTION_CONTRACTS)
.doc(newContractUid);
const creatorRef = firestore.collection(COLLECTION_USERS).doc(creatorId);
const recipientRef = firestore
.collection(COLLECTION_USERS)
.doc(recipientId);
const [creator, recipient, newContractDoc] = [
await transaction.get(creatorRef),
await transaction.get(recipientRef),
await transaction.get(newContractRef)
];
if (newContractDoc.exists) {
console.warn("Attempted to create contract with already taked UUID");
return Promise.reject(
"Attempted to create contract with already taken UUID"
);
}
contractData.creationDate = Date.now().toString();

transaction.set(newContractRef, contractData);
// Update recipient and creator with contract relations
transaction.update(creatorRef, {
contracts: _.concat(creator.data().contracts, newContractUid)
});
transaction.update(recipientRef, {
contracts: _.concat(recipient.data().contracts, newContractUid)
});
})

我有这段代码可以在我的 firestore 中创建一个新契约(Contract)。然后它将此契约(Contract)与两个用户(创建者和接收者)相关联。

但是我担心这行代码:

transaction.update(creatorRef, {
contracts: _.concat(creator.data().contracts, newContractUid)
});

是否有可能另一个用户在交易发生时写入 creator.data() 字段并使我的数据在此处无效。或者我在交易期间是否有写锁?

编辑:

嗯,我在 firebase 文档中看到了这个

For example, if a transaction reads documents and another client modifies any of those documents, Cloud Firestore retries the transaction. This feature ensures that the transaction runs on up-to-date and consistent data.

我认为这意味着我在这种情况下是安全的,但我不确定

最佳答案

Firestore 事务可防止并发写入。如果它检测到写入冲突,它会重试事务,因此您的事务处理程序可能会为单个写入操作调用多次。

关于javascript - 在 firebase 中同时更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53586772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com