1

I want to search for an specific string value in an document which is in an array.

Here is my database:

Databse

This is my code so far: But it returns 0 documents:

func changePhotoUrlInPosts(url: String) {

    let db = Firestore.firestore()
    let user = UserService.currentUserProfile!

    db.collection("posts")
        .whereField("username", isEqualTo: user.username)
        .getDocuments { (snapshot, error) in
            if let indeedError = error {
                print(indeedError.localizedDescription)
                return
            }

            guard let indeedSnapshot = snapshot else {
                print("snapshot is empty")
                return
            }

            for document in indeedSnapshot.documents {
                document.setValue(url, forKey: "photoUrl")
            }
    }
}

How can I go into my array in this document?

Thanks

3 Answers 3

1

Your screenshot is showing data in Realtime Database, but your code is querying Firestore. They are completely different databases with different APIs. You can't use the Firestore SDK to query Realtime Database. If you want to work with Realtime Database, use the documentation here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. But how to do it. Didn't found anything helpful in the Internet :(
There is lots of documentation for making queries in both databases.
0

There is author between posts and username field in your data structure. Your code means that right under some specific post there is username field.

So such code will work because date right undes post:

db.collection("posts").whereField("date", isEqualTo: "some-bla-bla-date")

In your case you have two options as I see:

  • duplicate username and place this field on the same level as date and guests.
  • re-write you code to check username inside author document.

Hope it will help you in your investigation.

Comments

0

So I changed my code to:

func loadData(url: URL){

    let ref = Database.database().reference().child("posts")
    let user = UserService.currentUserProfile!

    ref.queryOrdered(byChild: "author/username").queryEqual(toValue: user.username).observe(.value, with: { snapshot in
        if var post = snapshot.value as? [String : Any] {
            print("updated all Posts")
            post.updateValue(url.absoluteString, forKey: "photoUrl")
            print(post.values)


        }else{
            print("fail")
        }
})

}

It went through and I get the print statement of my values but the data didn't changed in the realtime database

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.