Home > Mobile >  How to query a Firestore collection with an array filter?
How to query a Firestore collection with an array filter?

Time:06-23

I was doing a query to get information about the user. I want to save in a state the documents that contain the user's id, the user's ids are in an array within the document, my database is like this:

enter image description here

I was doing a query like this:

const loadingInformation = async () => {

        db.collection('channels').get()
            .then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                    if (doc.data()?.users?.includes(user.id)) {
                        setInformation([...information, {
                            id: doc.id,
                            data: doc.data()
                        }
                        ])
                    }
                })
            })

    }

 useEffect(() => {
        loadingInformation();
    }, [])

the problem is that it only brings me one document and this user is in more than two collections, also, when updating the page, a push is made but from the same document.

I also saw in the documentation that there is a request something like that, but it doesn't work for me:

await db.collection('channels').where('users', 'in', [[user.id]]).onSnapshot(snap => {
            setInformation(snap.docs.map(doc => ({
                doc
            })))
        })

CodePudding user response:

In operator returns documents with field that can be equal to many values, not just one. For example, .where('country', 'in', ['France', 'Germany']) will return documents where country is equal to France or Germany. In operator is meant to be used on number and string field, not arrays. What you need is .where('users', 'array-contains', user.id). If you want to search for more than one user use 'array-contains-any' it works same as 'in' operator but for arrays.

  • Related