how to get the snapshot of collection ( "message" ) by Descending order using "orderBy" method in firebase js v9



here i trying to get the collection("messages") snapshot which conatains document, but i want to get the collections snapshot which shoud be order by "timestamp" feild of documents in decending order how could i do that useing js v9 of firebase

onSnapshot(collection(db,"channels",channelId,"messages"),(snapshot) => {
  setMessages( =>


You can use query() function to build a query and then orderBy() function to specify the Query Constraint. Try the following:

import { collection, query, onSnapshot, orderBy } from "firebase/firestore"

const colRef = collection(db, "channels", channelId, "messages"), orderBy('timemstamp', 'desc'))

const q = query(colRef, orderBy("timestamp", "desc"))

onSnapshot(q, (snapshot) => {
  setMessages( =>

Answered By – Dharmaraj

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More