0

Need to pull all documents where:

(from = me AND to = you) OR (from = you AND to = me) 

all sorted sort by timestamp.

Trying to create the capability to chat between two people sort of like what you have on your phone. Had planned on storing all messages from all people in one collection called “messages”. I am tripped up on an apparent firebase limitation of compound queries.

Have a firebase collection “messages” with fields “from”, “to”, “message” and "timestamp".

Tried several variations of stacked where's as well as “in” but not getting what I need.

Is this possible or will it require two queries?

This won't work because you can't have two 'in' clauses:

collectionRef = query(collectionRef, where("from", "in", [fromId, toId]), where("to", "in", [fromId, toId]))

And, this won't work because it just stacks the 'and' so the result is nothing:

collectionRef = query(collectionRef, where("from", "==", fromId), where("to", "==", toId))
collectionRef = query(collectionRef, where("from", "==", toId), where("to", "==", fromId))

Already read these which leads me to believe two queries are needed.

https://firebase.google.com/docs/firestore/query-data/queries

Firebase Firestore - OR query

BGMX
  • 25
  • 7

1 Answers1

0

Solution: In my opinion, running two queries then combining the results then sorting the combined result is very inefficient and less than ideal. Although probably needed in other cases, I think I came up with a much better solution for this use case.

  1. Create one field “fromTo” to hold the concatenated values of fromId and toId.
  2. Index that field.
  3. Use this query:
ref = collection(db, 'messages')
ref = query(ref, where("fromTo", "in", [fromId + toId, toId + fromId]))
ref = query(ref, orderBy("timestamp", "desc"))

Worked for me.

BGMX
  • 25
  • 7