Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore query for same value in multiple fields

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()
like image 839
Nawaz Mohamed Avatar asked Oct 18 '25 07:10

Nawaz Mohamed


1 Answers

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());
    });
});
like image 178
Atif Zia Avatar answered Oct 20 '25 23:10

Atif Zia