1

I want to make a Firestore call in a collection which excludes some values on a field. This is the snippet of code I wrote

db.collection("MyCollection")
    .order(by: "timestamp", descending: false)
    .whereField("timestamp", isGreaterThan: localTimestamp)
    .whereField("uid", notIn: [reportedUids, currentUid])
    .limit(to: 3)
    .getDocuments { (snapshot, error) in
        if let err = error{
            print(err.localizedDescription)
            return
        }
        var modelsData = [Model]()
        snapshot?.documents.forEach({ (doc) in
            
            let dict = doc.data()
            var model = Model()
            model.transformModelWith(dict: dict)
            modelsData.append(model)
        })
        
        let lastDocumentFetched = snapshot?.documents.last
        DispatchQueue.main.async {
            completion(modelsData, lastDocumentFetched!)
        }
    }
}

The error I get when running this is:

Invalid query. You have a where filter with an inequality (notEqual, lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) on field 'uid' and so you must also use 'uid' as your first queryOrderedBy field, but your first queryOrderedBy is currently on field 'timestamp' instead.'

And searching online it brings me here, my question is:

how can I approach this problem if I necessarily need to exclude some data from the query?

StackGU
  • 868
  • 9
  • 22
  • One question at a time, por favor. – El Tomato Oct 06 '21 at 21:57
  • changed it, it's one now, @ElTomato – StackGU Oct 06 '21 at 22:38
  • The said topic with 'here' suggests that you have to pick either 'order' or 'whereField' but both. You can sort your array by order of 'timestamp,' on your own, can't you? – El Tomato Oct 06 '21 at 22:48
  • The solution there is given by Frank van Puffelen. So it must be correct. – El Tomato Oct 06 '21 at 22:49
  • Correction: "but both" -> "but not both" – El Tomato Oct 07 '21 at 00:08
  • I'm sure this is the correct answer but I can't sort the array I got by timestamp because I'm not getting all the documents firsthand, instead, I'm paginating, and I need the documents I got being in the right order. The only possible option I have is to exclude documents that have uids I don't need. But it's really difficult to implement because If I need to exclude all the documents (max 3 since that is the limit) I need to make a new database call recursively and I don't know how to implement it with a completion handler – StackGU Oct 07 '21 at 17:32

1 Answers1

0

The error message says to put .whereField("uid", notIn: [reportedUids, currentUid]) as the first filter.

Tad
  • 889
  • 9
  • 23
  • that's not true, the error message says it's not possible to filter or order using 2 different fields at the same time using Firestore – StackGU Oct 10 '21 at 21:29