javascript - 在 firebase 中同时更新数组

标签 javascript firebase google-cloud-firestore

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

相关文章:

javascript - 使用指令获取 html 元素的值。在 Angular.JS 中

javascript - 检测用户点击与 jquery .click()

android - Android通知负载中的FCM,event_time

google-cloud-firestore - 集合查询(单个)是否比组集合查询更快?

flutter - 状态错误 : field does not exist within the DocumentSnapshotPlatform Flutter Firestore

swift - 如何将 SFTransscriptionSegment 数据添加到 Firebase Firestore?

javascript - NextSibling 如何运作?

javascript - 不同时区的倒计时器

ios - ionic 3 cordova ios 构建失败 'google/protobuf/Api.pbobjc.h' 找不到文件

java - 无法将 java.lang.String 类型的对象转换为 com.example.ezcompras.model.Lojas 类型