Anteos1
Anteos1

Reputation: 99

How to access array in Firestore v9

Articles I've read/tried before:

I have a Firestore that looks like this enter image description here

  1. The current feature I'm trying to implement is a block list. Whenever you go to the person's profile, you click block, and the person doing the blocking's UID is stored as the doc id and the blocked user's id is added to the "blockedUserId" array
  2. The home page displays all the posts and I've been trying to filter the displayed posts to not include posts from any of the users in that "blockedUserId" array
  3. How do I go about doing this correctly?

Here is the attempted code

query(
      collection(getFirestore(fireApp), "posts"),
      orderBy("uid"),
      where(
        "uid",
        "not-in",
        doc(getFirestore(fireApp), "block", "vXLCRjlhOVW6oFOJvtmML6OolKA2")
      )

Upvotes: 0

Views: 158

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

Firestore queries can only filter on values in the document itself, and values you explicitly pass in to the query. Your doc(getFirestore(fireApp), "block", "vXLCRjlhOVW6oFOJvtmML6OolKA2") creates a DocumentReference, so the query returns documents from posts that don't contain that document reference.

What you want to do instead is:

  1. Load the blocked UIDs
  2. Pass them to the query

So in code:

const myRef = doc(getFirestore(fireApp), "block", "vXLCRjlhOVW6oFOJvtmML6OolKA2");
const myDoc = await getDoc(myRef);
const blocked = myDoc.data().blockedUserId;
const q = query(
  collection(getFirestore(fireApp), "posts"),
  orderBy("uid"),
  where(
    "uid",
    "not-in",
    blocked
  )
)
// TODO: call getDocs or onSnapshot on q

Upvotes: 1

Related Questions