简体   繁体   中英

How write query for firestore when both 'OR' and 'AND' logic has to be used simultaneously?

I am trying to fetch chat data between two individuals from firestore database. let's say the two individuals are Chris and Sam .

I am trying to fetch data which holds the below condition:

(to =='Chris' AND from == 'Sam') OR (to == 'Sam' AND from == 'Chris')

Please guide me on how I can use both OR and AND logic in my firestore query.

Firestore doesn't support OR queries that way. You'll have to run 2 different queries in Firestore:

const colRef = collection(db, "chats");

// Query for (to =='Chris' AND from == 'Sam')
const q1 = query(colRef, where("to", "==", "Chris"), where("from", "==", "Sam"))

// Query for (to == 'Sam' AND from == 'Chris')
const q2 = query(colRef, where("to", "==", "Sam"), where("from", "==", "Chris"))

A workaround would be to store a key with value ChrisSam (or SamChris ) and use the in operator like this:

const q3 = query(colRef, where("field", "in", ["ChrisSam", "SamChris"]))

However, this will require you to have unique user names across the applications (or use the User IDs instead). Also make sure the security rules only allow these 2 to query these documents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM