4

Is it possible to query data in cloud firestore for same value in either of multiple fields of a document.

Example like this

await firestore()
      .collection('chats')
      .where('ownerUserId', '==', user.uid)
      .where('chatUserId', '==', user.uid)
      .orderBy('createdAt', 'desc')
      .get()

or to be more precise, something like this

await firestore()
      .collection('chats')
      .where('ownerUserId', '==', user.uid || 'chatUserId', '==', user.uid)
      // .where('chatUserId', '==', user.uid)
      .orderBy('createdAt', 'desc')
      .get()

1 Answer 1

2

For an OR condition we've to do multiple queries like this:

//We define an async function that takes user uid and return chats
async function getChatsByUserOrOwner(userId) {
      const chatsRef=firestore().collection('chats')
      const ownerChats = chatsRef.where('ownerUserId', '==', userId).orderBy('createdAt', 'desc').get();
      const userChats = chatsRef.where('chatUserId', '==', userId).orderBy('createdAt', 'desc').get();  
      const [ownerChatsSnapshot, userChatsSnapshot] = await Promise.all([
              ownerChats,
              userChats
            ]);
      const ownerChatsList = ownerChatsSnapshot.docs;
      const userChatsList = userChatsSnapshot.docs;
      const allChats = ownerChatsList.concat(userChatsList);
      return allChats;
  }

Now we'll call this function to get required result:

//We call the asychronous function
getChatsByUserOrOwner(user.uid).then(result => {
    result.forEach(docSnapshot => {
        console.log(docSnapshot.data());
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

As soon as I do multiple requests to the same ref I run into the following error, any idea: FirebaseError: Missing or insufficient permissions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.