【发布时间】:2022-01-19 01:11:02
【问题描述】:
在 Firebase Firestore 中,我有一个集合,其中每个文档都包含一个 id 数组和一个子集合;像这样:
collection: households
>>> doc: household1, members = [1]
>>> >>> collection entries
>>> >>> >>> entry 1, <data>
>>> >>> >>> entry 2, <data>
>>> doc: household2, members = [1, 2]
>>> >>> collection entries
>>> >>> >>> entry 3, <data>
>>> >>> >>> entry 4, <data>
>>> >>> >>> entry 5, <data>
我想查询用户 1 所属的所有条目。我想对听众进行此操作,以便在 (1) 家庭发生变化或 (2) 条目发生变化时更新我的数据。
我该怎么做?
我试过先查询对应的户,然后得到对应的条目,像这样:
// Loop trough all households of user
db.collection("households")
.where("members", "array-contains", uid)
.where("status", "==", "active")
.onSnapshot((snapshotChange) => {
// Loop trough entry of each household
snapshotChange.forEach((householdsDoc) => {
db.collection("households")
.doc(householdsDoc.id)
.collection("entries")
.onSnapshot((snapshotChange) => {
snapshotChange.forEach((doc) => {
// Prepare entry
let currentDoc = doc.data();
currentDoc["id"] = doc.id;
// Handle change according to type
snapshotChange.docChanges().forEach((change) => {
console.log(change.type, "change.doc.id", change.doc.id);
if (change.type === "added") {
this.entries.push(currentDoc);
} else if (change.type === "modified") {
let index = this.entries.findIndex(
(el) => el.id === change.doc.id
);
if (index > -1) {
this.entries.splice(index, 1);
}
this.entries.push(currentDoc);
} else if (change.type === "removed") {
let index = this.entries.findIndex(
(el) => el.id === change.doc.id
);
if (index > -1) {
this.entries.splice(index, 1);
}
}
});
});
});
对于这段代码,我从控制台得到这个:
如您所见,不知何故,某些 id 会多次到达。这是为什么呢?
【问题讨论】:
标签: javascript firebase google-cloud-firestore listener