【问题标题】:Vue Firestore query. How to avoid duplication when Firestore updates data?Vue Firestore 查询。 Firestore更新数据时如何避免重复?
【发布时间】:2022-01-01 11:28:34
【问题描述】:

在一个 ionic vue 应用中,我想显示一些来自 Firebase Firestore 的数据。

在 Firestore 中,我有一个集合 households 和一个子集合 entries。用户可以是一个家庭的成员,我想显示她所属的所有家庭的所有条目。

我的data 中有一个数组entries

data() {
  return {
    entries: [],
  };
},

我通过对 firebase 进行三个嵌套查询来填充这个数组:

  1. 获取当前用户
  2. 获取与当前用户关联的所有家庭
  3. 获取当前用户所有家庭的所有条目
beforeCreate: function () {
  auth.onAuthStateChanged((user) => {
    if (user) {
      // Get current uid
      let uid = user.uid;

      // Loop trough all households of user
      let userHouseholdIds = [];
      db.collection("households")
        .where("members", "array-contains", uid)
        .onSnapshot((snapshotChange) => {
          snapshotChange.forEach((doc) => {
            userHouseholdIds.push(doc.id);
          });

          userHouseholdIds.forEach((householdId) => {
            // Get household name
            db.collection("households")
              .doc(householdId)
              .get()
              .then((value) => {
                let householdId = value.id;
                let householdName = value.data().name;

                // Get household entries
                db.collection("households")
                  .doc(householdId)
                  .collection("entries")
                  .onSnapshot((snapshotChange) => {
                    snapshotChange.forEach((doc) => {
                      let newDoc = doc.data();
                      newDoc["id"] = doc.id;
                      newDoc["householdName"] = householdName;
                      newDoc["householdId"] = householdId;
                      this.entries.push(newDoc);
                    });
                  });
              });
          });
        });
    }
  });

虽然我不确定这是否是可行的方法,但它可以按预期工作(到目前为止)。

但是,当我直接在 Firestore 控制台中更改家庭 h1 中的条目 e1 时,来自 h1 的每个条目都会在前端重复。

我想,在 Firestore 更新到来之前,我需要一个 this.entries = [],但我不知道在哪里。

我在正确的轨道上吗?我需要修改什么以避免重复? 非常感谢!

【问题讨论】:

  • 嗨@Julian,您能否检查一下Firestore 中是否还有重复条目?
  • 不,Firestore 中没有重复条目;刷新后一切看起来都像预期的那样。

标签: javascript firebase vue.js google-cloud-firestore


【解决方案1】:

如果您必须使用“onSnapshot”,请检查 change.type

db
.collection(...)
.where(...)
.onSnapshot((snapshotChange) => {
    snapshotChange.docChanges().forEach(change => {
        if (change.type === 'added') {
          this.entries.push()
        } else if (change.type === 'modified') {
          this.entries.splice()
        } else if (change.type === 'removed') {
          this.entries.splice()
        }
      })
})

如果没有,请尝试使用 get()

db
.collection(...)
.where(...)
.get()

【讨论】:

  • 太好了,就是这样!
猜你喜欢
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多