logo
Firebase - Interview Questions and Answers
Write a query to fetch the 10 most recent posts from Firestore.

To fetch the 10 most recent posts from Firestore, assuming each post has a timestamp field (e.g., createdAt with a Firestore Timestamp), you can use the .orderBy() and .limit() functions.

Firestore Query (JavaScript) :
const db = firebase.firestore();

const postsRef = db.collection("posts")
    .orderBy("createdAt", "desc")  // Order by timestamp (newest first)
    .limit(10);  // Limit to 10 posts

const snapshot = await postsRef.get();

const posts = snapshot.docs.map(doc => ({
    id: doc.id,
    ...doc.data()
}));

console.log(posts);
* Explanation :

* orderBy("createdAt", "desc") → Sorts posts by createdAt in descending order (newest first).
* .limit(10) → Fetches only the latest 10 posts, improving efficiency.
* snapshot.docs.map(doc => doc.data()) → Converts Firestore snapshot to a usable JavaScript array.


Query with Pagination :

If you need pagination (e.g., fetching older posts), you can use .startAfter(lastDoc):

const firstBatch = await db.collection("posts")
    .orderBy("createdAt", "desc")
    .limit(10)
    .get();

const lastDoc = firstBatch.docs[firstBatch.docs.length - 1];

// Fetch the next batch of posts
const secondBatch = await db.collection("posts")
    .orderBy("createdAt", "desc")
    .startAfter(lastDoc)  // Start after last fetched document
    .limit(10)
    .get();

* This ensures efficient pagination instead of reloading everything.