【问题标题】:Firestore real-time remove or modifyFirestore 实时删除或修改
【发布时间】:2019-09-02 07:06:58
【问题描述】:

我将 Firestore 用于测试项目,只是想看看它有什么功能。一切都正常运行,除了我在运行数据库的实时功能时遇到了一些麻烦。首先,我初始化数据库并传入凭据。

创建一个新列表并将其添加到 div 元素中的文档中。然后我在我想要实时监控的集合上调用 onSnapshot() 方法。添加元素后一切正常,我很难找到如何为“删除”和“修改”路径做同样的事情..

如何实时监控正在删除或修改的项目?

// variables based on the newly created firebase db
const db = firebase.firestore();
const colRef = db.collection("werknemers");

// RETRIEVE RECORDS IN REAL TIME 
// I create a list and append it to the element 
var list = document.createElement('ol');
document.getElementById("check").appendChild(list);

// at changes in reference collection onSnapshot() is called 
colRef.onSnapshot(snapshot => {

    // Listen for document metadata changes
    includeMetadataChanges: true;

    // for each change in the document 
    snapshot.docChanges().forEach(function(change) {

      // adding functions 
      if (change.type == "added"){

        let list_item = document.createElement("li");
        list_item.className = "list_item_class";
        list.appendChild(list_item);
        list_item.innerHTML = change.doc.data().departement + " " +   change.doc.data().naam;

      }

      // removed is called, remove something from your list 
      else if (change.type == "removed"){

      }

      // modified is called 
      else if (change.type == "modified"){

      }
    }, function(error){

        console.log("an error has occurred during realtime change process");

  });
});

【问题讨论】:

  • 您使用的数据库是 Cloud Firestore,它是一个完全独立于实时数据库的数据库。虽然这两个数据库都是 Firebase 的一部分,但它们是独立的,并且每个都有自己的 API。请使用正确的产品名称和标签,以增加获得帮助的机会。
  • 谢谢你,弗兰克,我的错误.. 我感谢您的建议和编辑!

标签: javascript google-cloud-firestore


【解决方案1】:

您需要处理三种主要情况:

  1. 将文档添加到数据库后,您需要将该文档的元素添加到 HTML。
  2. 从数据库中删除文档时,您需要从 HTML 中删除该文档的元素。
  3. 在数据库中更新文档时,您需要在 HTML 中更新该文档的元素。

由于删除和更新要求您可以在 HTML 中找到文档的元素,因此您需要确保在 HTML 元素中包含文档 ID(通常作为其 ID)。

snapshot.docChanges().forEach(function(change) {
  if (change.type == "added"){
    let list_item = document.createElement("li");
    list_item.className = "list_item_class";
    list_item.id = change.doc.id;
    list.appendChild(list_item);
    list_item.innerHTML = change.doc.data().departement + " " +   change.doc.data().naam;
  }
  else if (change.type == "removed"){
    let list_item = document.getElementById(change.doc.id);
    if (list_item) {
      list_item.parentNode.removeChild(listItem);
    }
  }
  else if (change.type == "modified"){
    let list_item = document.getElementById(change.doc.id);
    if (list_item) {
      list_item.innerHTML = change.doc.data().departement + " " +   change.doc.data().naam;
    }
  }
}, function(error){
    console.log("an error has occurred during realtime change process");
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2013-05-31
    • 2020-11-11
    • 1970-01-01
    • 2011-09-08
    相关资源
    最近更新 更多