在 ionic vue 應用程序中,我想顯示來自 Firebase Firestore 的一些數據。
在 Firestore 中,我有一個households
帶有子集合的集合entries
。用戶可以是一個家庭的成員,我想顯示她所屬的所有家庭的所有條目。
我有一個數組entries
在我的data
:
data() {
return {
entries: [],
};
},
我通過對 firebase 進行三個嵌套查詢來填充這個數組:
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 控制台e1
中對家庭中的條目進行更改時,前端中的h1
每個條目h1
都會重複。
我想,this.entries = []
在 Firestore 的更新進來之前,我需要一個地方,但我不知道在哪裡。
我在正確的軌道上嗎?我需要修改什麼以避免重複?非常感謝!
如果您必須使用“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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句