【发布时间】:2021-12-09 15:31:40
【问题描述】:
环境:nodejs、firebase-admin、firestore。
创建新空间(示例):
// init data
const userId = "someUserId";
// Create new space
const spaceRef = await db.collection("spaces").add({ name: "SomeName" });
// Get spaceId
spaceId = spaceRef.id;
// Get user Doc for upate their spaces
const userRef = await db.collection("users").doc(userId);
// Add "spaceId" to user spaces list
userRef.collection("spaces").doc(spaceId).set({ some: "data" });
// Create collection "members" in new space with "userId"
spaceRef.collection("members").doc(userId).set({role: "OWNER"})
问题:我想在单个runTransaction 中执行这段代码,但是我看到事务只支持一次性读取和多次更新,这不适合我,因为我得到了@ 987654327@我在代码执行过程中需要。
我为什么要使用事务:在我的数据结构中,需要创建空间和该空间的ID在用户身上的存在之间的关系。如果我们假设在执行这段代码的过程中发生了错误,例如创建了空间,但是这个空间没有添加到用户配置文件中,那么这将是我的数据库结构中的致命问题。
与其他数据库类似,事务解决了这个问题,但我不知道如何使用firestore。
也许您知道在这种情况下保护自己免受一致数据影响的更好方法?
【问题讨论】:
标签: javascript node.js firebase google-cloud-firestore