0

My Firestore has a collection of Events which includes a Timestamp field, startDate. At the moment, there are 4 events: one today, two further in the future and one is dated 1 May 2020.

In my app, I only care about the Events that are not in the past. So, I've set up my query as follows:

let today = Date()
let todayMidnight = getMidnight(for: today)!
let todayTimeStamp = Timestamp(date: todayMidnight)

activitiesCollection
    .order(by: "startDate")
    .whereField("startDate", isGreaterThanOrEqualTo: todayTimeStamp)
activitiesCollection.addSnapshotListener { (snapshot, error) in

I've tried with and without the order(by:) clause.

After initially using todayTimeStamp in my query, I also tried specifying my date parameter as today and todayMidnight as per Frank's answer to this post.

That makes six variations (with/without sorting, three date constants), and in all cases, the query is returning every document in the collection, as if it's ignoring the query altogether.

What am I doing wrong? How can I return only the documents I want instead of all of them?

1
  • Make an event that has a Timestamp of yesterday to see if your whereField clause is not just returning events from today. Commented May 22, 2020 at 12:16

1 Answer 1

2

You're not storing the query you build, but instead are reading straight from the collection again.

You can either attach the listener straight to the query after you build it:

activitiesCollection
    .order(by: "startDate")
    .whereField("startDate", isGreaterThanOrEqualTo: todayTimeStamp)
    .addSnapshotListener { (snapshot, error) in

Or you can keep the query in a variable:

let query = activitiesCollection
    .order(by: "startDate")
    .whereField("startDate", isGreaterThanOrEqualTo: todayTimeStamp)
query.addSnapshotListener { (snapshot, error) in
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, God. Is it really that simple? I feel so embarrassed. I think I had that before but I was trying to "simplify my code" and combine the query definition with the listeners, not realizing it would have that effect. I'll try it right away. (And I knew you would be the one to set me straight.....)
Worked perfectly, as you said. "100 Points for Hufflepuff!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.