这是我的查询字符串数据结构。
数据结构
{
"root_firebase_DB": {
"users": [{
"meUID": {
"name": "ME",
"rooms": [{
"room_id_01": true
}]
}
}, {
"friendUID": {
"name": "FRIEND",
"rooms": [{
"room_id_01": true
}]
}
}],
"rooms": [{
"room_id_01": {
"meUID": true,
"friendUID": true
}
}],
"messages": [{
"room_id_01": {
"message_id_01": {
"text": "Hello world",
"user": {
"_id": "meUID",
"name": "ME"
}
},
"message_id_02": {
"text": "Xin Chao",
"user": {
"_id": "friendUID",
"name": "FRIEND"
}
}
}
}]
}
}
我有meUID
和friendUID
,我想找一个包含我们的房间。
const meUID = 'abc';
const friendUID = 'abc';
/**
* Find room key
* filter by meUID and friendUID
*
* THIS WAY I GOT WARNING .indexON
*
*/
firebase.database().ref()
.child('rooms')
.orderByChild(meUID)
.equalTo(true)
.on('child_added', snap => {
if (snap.hasChild(friendUID)) {
console.log('Got roomKEY', snap.key);
}
});
一般来说,我通过meUID
得到一系列房间并循环,每个循环我都会过滤以查找此房间是否有friendUID
,这样我没有警告有索引,但似乎浪费时间循环和检查所有房间。
/**
* THIS WAY NOT GET ANY WARNING
* BUT IS THERE OTHER GOOD WAY TO GO?
*/
const ref = firebase.database().ref();
const meUID = 'aaa';
const friendUID = 'bbb';
const messages = [];
ref.child(`users/${meUID}/rooms`).once('value', snap => {
const roomKey = null;
// loop all room that belong to me
snap.forEach(room => {
// with each room, i must going to check is this room belong to friendUID or not
ref.child(`users/${friendUID}/rooms/${room.key}`).once('value', friendRoomSnap => {
if (friendRoomSnap.val()) {
// found room that belong to friendUID too
roomKey = room.key;
}
});
if (roomKey != null) {
//if found that room, break the loop
return true;
}
});
// goto fetching all messages in this room
ref.child(`messages/${roomKey}`).on('child_added', messageSnap => {
messages.push(messageSnap.val());
});
});
//Too much stuff, is there any way better?
请帮助,我是新手。
我的数据结构是否出现问题?