我正在使用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");
});
});
答案 0 :(得分:0)
您需要处理以下三种主要情况:
由于删除和更新要求您可以在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");
});