Firestore 批处理/事务不是原子的,具有多个集合,请在 Cloud Function 内删除

问题描述 投票:0回答:1

我想使用 Firestore Web API 在 Cloud Function 内批量删除和创建集合(子集合)中的多个文档。我的云函数内的代码如下所示(TypeScript):

const collectionRef = db.collection('my_collection');
const batch = db.batch();
batch.delete(collectionRef.doc('doc01'));
batch.set(collectionRef.doc('doc02'));
await batch.commit();

在我的 Web 客户端中,我使用

react-firebase-hooks
实时查看集合更新(TypeScript、React.js):

const [docs, loading, error] = useCollectionData(collection(db, 'my_collection'));

有关事务和批次的Firestore 文档指出,它们应该自动完成写入操作。但这不是我观察到的。当我调用我的云功能时,我在客户端上观察到单独的更新:

  1. docs
    已更新以包括“doc01”和“doc02”。
  2. docs
    再次更新,现在没有“doc01”。

我还在本地 Firestore 模拟器中的

http://localhost:4000/firestore/default/data/my_collection
处看到了这一点,
doc02
出现在列表中的时间早于“doc01”被删除的时间。

如果我更改云功能代码以使用事务,也会发生同样的情况:

const collectionRef = db.collection('my_collection');
await db.runTransaction(async (transaction) => {
  transaction.delete(collectionRef.doc('doc01'));
  transaction.set(collectionRef.doc('doc02'));
});

我希望

delete
set
一起完成,而不看到任何部分结果。我做错了什么?

reactjs firebase google-cloud-firestore google-cloud-functions react-firebase-hooks
1个回答
0
投票

很难确定,因为您实际上没有表现出有问题的行为,但很可能您看到的是本地写入的事件。 Firestore SDK 乐观地在执行写入的客户端上触发事件。您可以检查快照元数据是否有挂起的写入来捕获此情况。

© www.soinside.com 2019 - 2024. All rights reserved.