Home > Mobile >  Firebase Database V9 Return last item
Firebase Database V9 Return last item

Time:03-22

I have a chat system where a chat contains multiple messages the structure looks like this below:

 - messages
   - ChatId123
      - MesageId123
      - MessageId456

I just want to retrieve the last message sent in this case MessageId456 I assume I need to use orderByKey(). The keys are generated using push() how can I correctly query and filter for the last item?

const query = query(ref(db, `messages/ChatId123`), orderByKey())
return query

CodePudding user response:

the easiest way would be to add timestamp field in the message object like "SendAt" and orderBy this value :


const q = query(ref(db, `messages/ChatId123`), orderBy("SendAt", "desc"), limit(1));


example Firestore side

CodePudding user response:

You can use limitToLast to get just the last item(s) from a query:

query(ref(db, `messages/ChatId123`), orderByKey(), limitToLast(1))

For more on this, see the Firebase documentation on filtering data.

  • Related