我正在使用以下结构的Firebase实时数据库。我希望获取用户访问和订阅这些注释中的更改的所有“注释”。
notes: {
"noteId-1345" : {
"access" : {
"author": "1234567890"
"members": {
"1234567890": 0 <--- Author
"0987654321": 1 <--- Member
}
},
"data" : {
"title": "Hello",
"content": "Konichiwa!",
"comment": "123"
}
}
}(我知道,理想情况下,这种结构可能更平坦。*)
为了获取用户可以访问的所有注释,我在根目录中保留了一个额外的user_notes节点:每当我将一个用户(members的更新)与一个便笺相关联时,我都会更新/notes/$noteid和/user_notes/$uid。
user_notes: {
"$uid": {
"noteId-1345": {
myHide: false,
mySortOrder: 0,
title: "Hello"
}
}
}在获取数据时,我希望设置对用户可以访问的所有注释的订阅。
首先,获取用户可以访问的便笺的in,然后附加侦听器,以订阅每个note中的更新。
const uid = getState().auth.uid
let collectedNotes = {}
...
database.ref(`user_notes/${uid}`).on('value', (myAccessSnaps) => {
myAccessSnaps.forEach((accessSnap) => {
const noteId = accessSnap.key
const privateData = {'personalData': {...accessSnap.val()}}
database.ref(`notes/${noteId}`).on('value', (noteSnap)=>{
const notData = noteSnap.val()
const fullData = { ...privateData, ...notData }
const note = {
id: noteSnap.key,
...fullData
}
collectedNotes[note.id] = note
...
})
}))
})(当然,在设置新监听器之前,我需要使用.off()来分离监听器)
这有点问题,因为我必须为每个note附加一个侦听器-而且数据库中可能有数百个注释。这是最有效的方法吗?-这看起来效率很低。
有没有一种方法可以听所有的--用户在/notes路径中使用one侦听器访问的注释?还是我的做法完全错了?)
亲切问候/K
发布于 2020-11-10 16:17:37
在理解了.on() does not return a promise之后,我变得更容易解决我的问题了。
附加许多.on()侦听器对我来说没有任何意义。
对我来说最简单的方法是:
每次更新便笺时,使用时间戳updatedAt更新我的访问节点
2-使用返回承诺的.once()加载初始数据,请参阅下面的代码。
3-为访问节点更改设置单独的订阅。
let myPromises = []
database.ref(`user_notes/${uid}`).once('value', (myAccessSnaps) => {
myAccessSnaps.forEach((accessSnap) => {
const noteId = accessSnap.key
const privateData = {'personalData': {...accessSnap.val()}}
myPromises.push(
database.ref(`notes/${noteId}`).once('value', (noteSnap)=>{
const notData = noteSnap.val()
const fullData = { ...privateData, ...notData }
const note = {
id: noteSnap.key,
...fullData
}
collectedNotes[note.id] = note
...
})
)
}))
})
return Promise.all(myPromises)
.then(() => {
dispatch(setNotes(categories))
...
// Set up subscription after initial load
database.ref(`user_notes/${uid}`).on('value', (myAccessSnaps) => {
...
// Use access node listener only - gets updated by 'updatedAt'
database.ref(`notes/${noteId}`).once('value', (noteSnap)=>{
//Collect and dispatch data亲切问候/K
https://stackoverflow.com/questions/64728791
复制相似问题