javascript - 使用之前的状态更新 firestore

标签 javascript firebase google-cloud-firestore

是否可以使用以前的状态更新firestore?

例如,我有一个地址文档,其中有一个 users 字段,其中包含与该地址关联的用户数组。 每当我想向此数组添加新用户时,我都需要以前的数组,否则我最终会用新数据覆盖当前数据。

所以我最终得到了类似的结果。

   firestore()
    .collection("addresses")
    .doc(addressId)
    .get()
    .then(doc => {
      this.db
        .collection("addresses")
        .doc(addressId)
        .update({
          users: [...doc.data().users, id]
        })
    });

有没有一种方法可以访问以前的数据而无需嵌套调用?

如果没有

有没有更好的方法来管理关系?

最佳答案

如果您需要以前的值来确定新值,则应使用 transaction 。这是确保不同客户端不会意外覆盖彼此操作的唯一方法。

不幸的是,事务还需要嵌套调用,因为这是获取当前值的唯一方法,甚至还有一个额外的包装器(用于事务。

var docRef = firestore()
    .collection("addresses")
    .doc(addressId);

return db.runTransaction(function(transaction) {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(docRef).then(function(doc) {
        transaction.update(docRef, { users: [...doc.data().users, id ]});
    });
}).then(function() {
    console.log("Transaction successfully committed!");
}).catch(function(error) {
    console.log("Transaction failed: ", error);
});

最佳解决方案是使用不需要当前值即可添加新值的数据结构。这就是原因之一Firebase recommends against using arrays :当多个用户可能向数组添加项目时,它们本质上很难扩展。如果不需要维护用户之间的顺序,我建议为用户使用类似集合的结构:

users: {
  id1: true,
  id2: true
}

这是一个包含两个用户(id1id2)的集合。 true 值只是标记,因为字段不能没有值。

通过这种结构,添加用户就像这样简单:

firestore()
    .collection("addresses")
    .doc(addressId)
    .update({ "users.id3": true })

另请参阅Firestore documentation on Working with Arrays, Lists, and Sets

关于javascript - 使用之前的状态更新 firestore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129052/

相关文章:

php - jQuery 的工具提示问题

JavaScript 全局动态变量从函数到函数未定义,似乎是局部范围

android - 使用 fragment 的不同方式

angularjs - 将 Firestore 集合和子集合文档数据放在一起

android - 恢复缓存数据 RecyclerView + Firestore

javascript - 与原型(prototype)结构相比,经典结构有哪些优势?

javascript数组indexOf不工作

javascript - 如何防止 Firestore 索引出现多种组合

firebase - 在列表中添加元素

ios - IOS 上 Firebase 的 GoogleService-Info.plist 中缺少 CLIENT_ID、REVERSED_CLIENT_ID 和 ANDROID_CLIENT_ID