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()
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());
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With