Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

swift - Why does this query return nil from Firestore

I am trying to get the three most recent documents from my collection group userPosts using the following database structure and query:

-posts
   -{userID}
      -userPosts
         -{documentID}
            -postTime(Field)

Query:

postQuery = Firestore.firestore()
            .collectionGroup("userPosts")
            .order(by: "postTime", descending: true)
            .limit(to: 3)

function used to query Firestore:

func loadPosts() {
    postQuery.getDocuments{ [weak self](querySnapshot, error) in
        self!.q.async{
            var postsTemp = self?.postArray
            for doc in querySnapshot!.documents{
                self?.documents += [doc]
                let post = self!.createPost(doc)
                if(!self!.postArray.contains(post)){
                    postsTemp?.insert(post, at: 0)
                }
                 
                DispatchQueue.main.async {
                    self!.postArray = postsTemp!
                    self!.tableView.reloadData()
                }
            }
        }
    }
}

However when I run this I get an error due to the fact that querySnapshot is nil. I am not sure why this happens since when I change descending to false I get a result but in the opposite order that I want. I have a feeling it has something to do with my query but am not sure where I went wrong.

question from:https://stackoverflow.com/questions/65893126/why-does-this-query-return-nil-from-firestore

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The getDocuments callback gets called with two values (querySnapshot and `error), only one of which will have a value.

You're ignoring the error and assuming that querySnapshot has a value, which not only leads to the error you get, but also hides the likely cause.

I recommend following the pattern used in this example from the Firestore documentation on getting documents:

db.collection("cities").whereField("capital", isEqualTo: true)
    .getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: (err)")
        } else {
            for document in querySnapshot!.documents {
                print("(document.documentID) => (document.data())")
            }
        }
}

By logging the error you can see what went wrong with your getDocuments() call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...