0

I use firebase realtime database and this is my structure.

enter image description here

My question is how can i get last 20 messages ordered by createdAt for every group. Any suggestions?

function getLastMessages(userId: string): Promise<any> {
    return new Promise(function (resolve, reject) {

        const dbRef = firebase.database().ref();

        dbRef.child("Users").child(userId).get().then((snapshot) => {
            if (snapshot.exists()) {
                resolve(result);
            } else {
                console.log("No data available");
                resolve([]);
            }
        }).catch((error) => {
            reject(error);
            console.error(error);
        });
    });
}

I cant figure out how to fetch last 20 records ordered by createdAt for every group.

Selvi Manafov
  • 25
  • 1
  • 5
  • Can you show what you already tried and where you got stuck? – Frank van Puffelen Apr 21 '21 at 14:00
  • Just updated the question. – Selvi Manafov Apr 21 '21 at 14:12
  • Thanks, that helps! So you want to get the latest 20 messages across all groups? That is not going to be possible with your current data structure, as Firebase can only query across a flat list of messages and you have two unknown levels in your JSON under the UID before you get to the createdAt`: group ID and message ID. Also see https://stackoverflow.com/questions/27207059/firebase-query-double-nested – Frank van Puffelen Apr 21 '21 at 14:32

0 Answers0