Firestore实时删除或修改

时间:2019-09-02 07:06:58

标签: javascript google-cloud-firestore

我正在使用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");

  });
});

1 个答案:

答案 0 :(得分:0)

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

  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");
});
相关问题