SwiftUI中如何使用Cloud Firestore判断查询是否返回文档

ix0qys7i  于 2023-03-28  发布在  Swift
关注(0)|答案(1)|浏览(110)

我尝试从我的“用户”集合中随机选取一个文档。为了实现这一点,我尝试遵循“双向”方法,概述如下:Firestore: How to get random documents in a collection .
下面是我迄今为止尝试实现该方法的代码:

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)
        }
    }

然而,我很难弄清楚var 'query'是否真的获得了一个文档,我需要在进入方法的下一步之前知道这个信息。

bwleehnv

bwleehnv1#

您可以在query.getDocuments中检查**querySnapshot.isEmpty**,如下所示:

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())")
            }
        }
    }
}

有关详细信息,请参阅从集合中获取多个文档

相关问题