Skip to content

Firebase

andreiradchenko edited this page Mar 9, 2024 · 1 revision

Filtering data from Firestore

Firestore query doc | How to query nested objects in firestore

When you will try to perform query with where('author.id', '==', user.id) prop, you'll be asked about adding new index in you firestore DB.

firestore DB index

Example of the query with filtering by author.id:

import {
  collection,
  query,
  orderBy,
  startAfter,
  limit,
  getDocs,
  Timestamp,
  where,
} from 'firebase/firestore';

export const getPaginatedUserPosts = async (lastVisible, limits, user) => {
  let documentSnapshots = null;

  const q = lastVisible
    ? query(
        postsCollection,
        where('author.id', '==', user.id),
        orderBy('timestamp', 'desc'),
        startAfter(Timestamp.fromMillis(lastVisible)),
        limit(limits)
      )
    : query(
        postsCollection,
        where('author.id', '==', user.id),
        orderBy('timestamp', 'desc'),
        limit(limits)
      );

  try {
    documentSnapshots = await getDocs(q);
    return documentSnapshots;
  } catch (e) {
    console.log(e.message);
  }
};