Xwingoga06
Xwingoga06

Reputation: 101

How can I query the length of my array with firestore?

this is my object

readUserIDS:[
    0: ID1
    1:ID2
]

or

readUserIDS:[
    0: ID1
]

I wanna render just the array with 1 ID but I don't know how to query my array with firestore. Basically, I wanna find just the array.length with one ID

  const notification = () => {
    channelsRef
      .where('channelID', '==', item.id)
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          doc.ref
            .collection('thread')
            .where('senderID', '==', item.participants[0].id)
            .where('readUserIDs.2', '>', '')
            .get()
            .then((querySnapshot) => {
              console.log('size', querySnapshot.size);
              querySnapshot.forEach((thread) => {
                let data = querySnapshot.size;
                console.log('data', data);
              });
            });
        });
      });
  };

Upvotes: 0

Views: 364

Answers (1)

Broda Noel
Broda Noel

Reputation: 1960

Edit in April 25 2023:

Now we can use the .count() function. Check documentation in https://firebase.google.com/docs/firestore/query-data/aggregation-queries.

This is quite useful because it avoids retrieving all the collection items from the DB. Cheaper and faster.


Old answer:

  const notification = () => {
    channelsRef
      .where('channelID', '==', item.id)
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          doc.ref
            .collection('thread')
            .where('senderID', '==', item.participants[0].id)
            .where('readUserIDs.2', '>', '')
            .get()
            .then((querySnapshot) => {
              return querySnapshot.size;
            });
        });
      });
  };

Upvotes: 2

Related Questions