'How to set specific query parameters for docs in a sub collection in firestroe 9?

How to set a specific quarry for a sub collection when using a snapshot ? I am tring to sort sub collection resutls by createdAt with the limit of last 5

 useEffect(() => {
      //const querydata = query(docRefComm, orderBy('createdAt'), limit(5));
      let collectionRef = collection(db, 'Comm', docId, 'messages');
      const unsub = onSnapshot(collectionRef , (doc) => {
       doc.forEach((el) => {
          console.log(el.data());
        });
      });
      return () => {
        unsub();
      };
    }
  }, []);


Solution 1:[1]

You can build a query() using CollectionReference as shown below:

let collectionRef = collection(db, 'Comm', docId, 'messages');
const q = query(collectionRef, orderBy('createdAt'), limit(5))
      
const unsub = onSnapshot(q , (qSnap) => { 

})

Checkout Listen to multiple documents in a collection in the documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharmaraj