1

Hi I am pretty new to Firebase real time database and this is my first project. Sorry if this is a stupid question.

I am saving my data as follows.

firebase database structure:

image

Now I want to retrieve all parent chat ids on which the student is participating, using the student_id variable.

I tried as per this SO question and this structure database and retrieve data documentation, but its not retrieving values. Anybody have an idea?

1 Answers1

0

I would suggest saving the chatroom IDs your students are in in a separate location. For example:

Path:
“/users/$uid/chatrooms”
Data:
{
0: 350,
1: 423
}

Thus you could retrieve the chat room ids first before getting the chatroom data.

import { initializeApp } from “firebase”;
 import { getDatabase, get, set, ref } from “firebase/database”;


const userChatroomIdsRef = ref(db, ‘/users/${uid}/chatrooms‘);
get(userChatroomIdsRef).then(result => {
const chatroomIds = result.val();
if (!(chatroomIds && chatroomIds instanceof Array)) return; // firebase will return null if its an empty array. 
const getChatroomInfoPromises = chatroomIds.map(id => get(ref(db, ‘/chat/${id}/${uid}’)).then(result => result.val());
Promise.all(getChatroomInfoPromises).then(chatroomInfoArray => { YOUR LOGIC HERE });
});

Removing/adding students from/to chatrooms would now be simple as you could just change the array of chatroomIds.

const userChatroomIdsRef = ref(db, ‘/users/${uid}/chatrooms‘);
get(userChatroomIdsRef).then(result => {
const oldIds = result.val();
const newChatroomIds = oldIds.filter(id => id !== ID TO DELETE);
return set(userChatroomIdsRef, newChatroomIds)
});

This is of course assuming that you know the uid of your student_id. If you do not know what uid each student_id has, you must must store a reference. I would suggest saving all student info in the “/users/$uid/” directory. Here you could save the studentId so you can programmatically use it.

In all other firebase logic I would try to use the native firebase uid for querying. This will make your life easier.

It’s always good the keep information organized on the database so your logic is simple.

Please check my code for syntax errors; I wrote this on an iPhone.