.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/