Firestore query not receving updates on create new doc

Viewed 123

I have a Firestore query and, I need it to listen to the creation of new documents, I tried many possibilities but couldn't make it work, every time I create a document the listener is not triggered. This is my listener code:

firestore
        .collection("users")
        .document("123")
        .collection("images")
        .whereField("postId", isEqualTo: "123")
        .order(by: "createdAt", descending: true)
        .limit(to: 1)
        .addSnapshotListener { [weak self] snapshot, error in
            guard let imageDocument = snapshot?.documents.first else {
                return
            }
            // this print statement is only being called once (not being called when creating a new doc)
            print(imageDocument)
        }
...

And this is my query to create the document:

firestore
    .collection("users")
    .document("123")
    .collection("images")
    .document()
    .setData([
        "postId": "123",
        "imageUrl": "....",
        "createdAt": Timestamp()
    ]) { error in
       guard let error = error else { return }
       print(error)
    }

My goal is that this listener is triggered when I create a new document in the Firestore.

Also, if I remove the limit from my listener query, the code works, but I will spend a lot of reads unnecessarily.

2 Answers

The problem is not about the way you are adding data to Firestore, but how you reading it. There is nothing related to the "limit(to: 1)" call either. When you perform the following query:

firestore
    .collection("users")
    .document("123")
    .collection("images")
    .whereField("postId", isEqualTo: "123")
    .order(by: "createdAt", descending: true)
    .limit(to: 1)

It means that you want to get all documents from the "images" sub-collection where the "postId" field holds the value of "123", and right after that, you order the results according to the "createdAt" field descending and limit the result to "1".

To be able to make such a query work, you have to create an index for it, otherwise, it won't return any results. You can create the required index manually in your Firebase Console:

enter image description here

Or you'll find in your IDE a message that looks like this:

FAILED_PRECONDITION: The query requires an index. You can create it here: ...

You can simply click on that link or copy and paste the URL into a web browser and your index will be created automatically for you.

The code should remain unchanged.

You have limit(to: 1) in your query. Try removing it.

Related