Search code examples
javascriptfirebasegoogle-cloud-firestorereact-native-firebase

How to user filter with Firestore database in React Native?


I want to filter the firestore query to get all docs that do not contain a specific value.

I used @react-native-firebase

import firestore from '@react-native-firebase/firestore';

  const getUnreadDocs = async () => {
    const unreadDocs = await firestore()
      .collection('rooms')
      .doc('aDRKtxbhG9g5IfbKcsa4')
      .collection('messages')
      .where('seen', 'not-in', ['7B6jaZngXeN7V4r3eRoDBdlcj6m2'])
      .get();

    console.log(`unreadDocs`, unreadDocs);
  };

docs return from the query

data-from-query

query-return-from-docs

How data is stored?

we have collection

rooms Collection -> Docs -> fields
         |
         V
     messages Collection -> Docs -> fields

rooms-collection-img

messages-collection-img1

messages-collection-img2

What should the query return? as we mention in query, docs should not contain 7B6jaZngXeN7V4r3eRoDBdlcj6m2 in the seen field

so, query should return only one doc i.e.

messages-collection-img1


Solution

  • The in/not-in operators checks if a current single-value field has a value that exists/does not exist in a list of values you specify. But your seen field is an array, which won't work with this operator.

    Instead you'll want to use array-contains on that to check if a value is present. There is no equivalent array-does-not-contain operator to check whether a value is not present in the array field.

    Also see: