Reputation: 105
I'm making a booking chatbot and i want to know the two near availables dates to booking if one date is not available.
I had tryied with
db.collection("horaries")
.where("startat", "==", dateTime)
.get()
.then(function(querySnapshot) {
if (querySnapshot.empty) {
return db.collection("horaries")
.where("startat", "<", dateTime)
.where("startat", ">", dateTime)
But it is returning empty all the time, it is work when dont have the where twice, but when i add the other where clause to make != clause it is returning empty. How can i make it work? And if this is not possible anymore, what approach can i do? i want to give the near date to expected booking date, sometimes the nearest it is on top and sometimes the nearest it is on bot so i really want to do this query.
Upvotes: 0
Views: 25
Reputation: 599571
If you add multiple conditions to a query in Firestore, the conditions are combined with an AND operation. So your query is asking for horaries
start before dateTime
AND after dateTime
. This is an empty set, because no single value can be before and after at the same time.
The common approach to get a single closest item is to combine two queries: one that queries for the first item before, and another that queries for the first item afterwards:
db.collection("horaries")
.where("startat", "<=", dateTime)
.get()
.then(function(querySnapshot) {
if (querySnapshot.empty) {
db.collection("horaries")
.where("startat", ">", dateTime)
.get()
.then(function(querySnapshot) {
...
As you can see, this uses the same number of queries as you already have, since I combined the equality check into the first query.
Upvotes: 1