1

On photo below you can see my data structure.

I want to get the required data from the messages object in one request. For example:

firebase.database().ref('messages/' + "-Me4yNAigYmM5_PhuiIS", 'messages/' + -Me4yNoy8n971XMwnxqP).get();

expected output:

{
   -Me4yNAigYmM5_PhuiIS: {
       text: example;
   },
   -Me4yNoy8n971XMwnxqP: {
       text: example2;
   },
}

I got out of the situation like this:

   useEffect(() => {
    const usersMessages = firebase.database().ref("users/" + userUid + "/messages");
    usersMessages.on('value', async (snapshot) => {
        let usersMessages = [];
        const messages = (await firebase.database().ref("messages/").get()).val();
       
        snapshot.val().map(messageId => {
            usersMessages.push(messages[messageId]);
        });
    });
}, []);

How correct is it to constantly load all messages of all users? Is there a way to get only the required messages from Firestone in one request, knowing a few message IDs?

enter image description here

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Danial
  • 45
  • 3

1 Answers1

1

To load multiple nodes based on their key, you'll need a separate call for each node/key. It's essentially a client-side join of the data from the two nodes:

const usersMessages = firebase.database().ref(`users/${userUid}/messages`);
usersMessages.on('value', async (snapshot) => {
    let usersMessages = [];
    snapshot.forEach((child) => }
        let messageId = child.key;
        let messageSnapshot = await firebase.database().ref(`messages/${messageId}`).get()
        const message = messageSnapshot.val();
        usersMessages.push(message);   
    });
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • All the same, we use one request for each message? – Danial Jul 08 '21 at 12:54
  • 1
    Yes. Contrary to what you may think, this is not necessarily slower than doing them in a single request, as Firebase can pipeline the requests over a single connection. To learn more about this, see https://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 – Frank van Puffelen Jul 08 '21 at 12:57