Home > Software design >  Querying based on doc id in firestore cloud functions doesn't return any result
Querying based on doc id in firestore cloud functions doesn't return any result

Time:10-23

I'm trying to query Firestore with a onDelete trigger. I'm getting the deleted doc's id.

This is a user doc and I want to fetch the 'friends' of that deleted user. Friends is an array in a user document. For hours, I have been trying many solutions I've seen to get those friends but none of them worked.

What I have tried:

  • const friendsOfDeletedUser = await fs
        .collection("users")
        .where(
          "friends",
          "==",
          fs.collection("users").doc(ctx.params.userId).id
        )
        .get();
    
    
  • const friendsOfDeletedUser = await fs
       .collection("users")
       .where(
         "friends",
         "array-contains",
         fs.collection("users").doc(ctx.params.userId).id
       )
       .get();
    
  • const friendsOfDeletedUser = await fs
        .collection("users")
        .where(
          "friends",
          "==",
          fs.collection("users").doc(ctx.params.userId).path
        )
        .get();
    
  • const friendsOfDeletedUser = await fs
        .collection("users")
        .where(
          "friends",
          "==",
          "/users/"   ctx.params.userId
        )
        .get();
    
  • const friendsOfDeletedUser = await fs
        .collection("users")
        .where(
          new FieldPath("friends"),
          "==",
          fs.collection("users").doc(ctx.params.userId).id
        )
        .get();
    
    

These friends array contain the other users' ids as doc reference.

Interestingly, when I put those fields as a normal doc property, the query still didn't return anything. I suspect something about the firestore versions and not properly queryig. Because the stuff I've tried should have been working in some versions of FS.

I'm running the queries in local emulator.

I must be overseeing something very obvious. Thanks in advance.

CodePudding user response:

If friends is an array of DocumentReference then you need that reference when querying and not the document ID.

const friendsOfDeletedUser = await fs
  .collection("users")
  .where(
    "friends",
    "array-contains",
    fs.collection("users").doc(ctx.params.userId) // no .id or .path
  )
  .get();

This will return all documents where friends array contains reference to deleted user.

  • Related