0

I'm trying to randomly pick a document from my 'users' collection. To accomplish this, I'm trying to follow the 'Bi-directional' method, outlined here: Firestore: How to get random documents in a collection.

Here's the code that I have so far trying to implement that method:

func obtainRandom() {
        let db = Firestore.firestore()
        
        let collectionRef = db.collection("users")
        
        collectionRef.getDocuments { snapshot, error in
            guard let documents = snapshot?.documents, !documents.isEmpty else {
                // Handle error or empty snapshot
                return
            }
            
            var randomNum = Int(arc4random_uniform(1000000)) + 1000000

            var query = collectionRef.whereField("random", isLessThanOrEqualTo: randomNum)
                .order(by: "random", descending: true)
                .limit(to: 1)
        }
    }

However, I'm having trouble figuring out whether the var 'query' actually obtains a document or not and I need to know this information before moving onto the next step in the method.

LuLuGaGa
  • 13,089
  • 6
  • 49
  • 57
Sutton
  • 53
  • 3

1 Answers1

1

You can check for querySnapshot.isEmpty in query.getDocuments as follows :

let db = Firestore.firestore()
let collectionRef = db.collection("myCollection")

let query = collectionRef.whereField("random", isLessThanOrEqualTo: randomNum)
    .order(by: "random", descending: true)
    .limit(to: 1)

query.getDocuments { (querySnapshot, error) in
    if let error = error {
        print("Error getting documents: \(error)")
    } else {
        if querySnapshot!.isEmpty {
            print("No documents found")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
            }
        }
    }
}

For more information go through Get multiple documents from a collection

Rohit Kharche
  • 2,541
  • 1
  • 2
  • 13