Fetch List of User Ids From Nested Collection in Firestore Database using TypeScript (NestJs)

274 Views Asked by At

I am working on firestore and my firestore collection structure as below:

Users-> userId1 -> UserDetails -> User_Info -> JSON Data

Users-> userId2 -> UserDetails -> User_Info -> JSON Data

Users-> userId3 -> UserDetails -> User_Info -> JSON Data

Users-> userId4 -> UserDetails -> User_Info -> JSON Data

For better understanding, please have a look in below snapshot:

enter image description here

Now I need a firestore query to fetch the list of userIds who has isCardOrdered is true.

The result should be:

[
"userId1",
"userId2",
"userId3",
"userId4"
]

I am doing this, but I am not getting the correct result.

@Injectable()
export class UsersClient {
    constructor(
        @Inject(UsersClientDocument.collectionName)
        private UsersCollection: CollectionReference<UsersClientDocument>,
    ) { }
   
   
   
        async fetchByQuery(query) {
            console.log('******************************');
            const querySnapshot = await this.UsersCollection.where('cardInfo[0].isCardOrdered', '==', true).get();
            querySnapshot.forEach((doc) => {
                console.log(' **********fetchByQuery:',doc.id, ' => ', doc.data());
        });
    }
    
    
}

And I am calling this method like this:

    const fireBaseUser: any = await this.UsersClient.fetchByQuery();
    console.log('fireBaseUser:',fireBaseUser);

Request: Any help would be appreciated. Thanks

1

There are 1 best solutions below

4
On

It looks like your cardInfo is an array, and Firestore doesn't support querying an item in an array in the way that you are trying here:

this.UsersCollection.where('cardInfo[0].isCardOrdered', '==', true).

Is you want to allow this query, you'll have to (also) store that value in a field that Firestore can query. For example, if you add an additional top-level field isCardZeroOrdered, you could query on that:

this.UsersCollection.where('isCardZeroOrdered', '==', true).

You could also store the info in a map field, rather than an array, which would visually look very similar, but would then allow you to query with:

this.UsersCollection.where('cardInfo.zero.isCardOrdered', '==', true).