1

I have a posts node that holds individual posts in my FB Database. These posts each have an array of users_liked that has a randomly generated key and the value is the current users uid. My problem is that I want to be able to check if the value (the uid) already exists in this array and if so, do something; otherwise do something else

How do I achieve this? My JSON tree is below. Thank you. enter image description here

AL.
  • 36,815
  • 10
  • 142
  • 281
Jimmy
  • 285
  • 3
  • 11
  • Firebase does not have an ability to check if a specific value exists. If you need this, it typically means you should invert the `users_liked` and use the UID as the key. See https://youtu.be/66lDSYtyils?t=6m17s and http://stackoverflow.com/questions/39149216/firebase-security-rules-to-check-unique-value-of-a-child-askfirebase – Frank van Puffelen Mar 22 '17 at 20:39

2 Answers2

2

Just request a snapshot for that path and use .exists().

var postid = "-KGNY..."
var uid = FIRAuth.auth()?.currentUser?.uid
var ref = FIRDatabase.database().reference()

ref.child("posts").child(postid).child("users_liked").child(uid!)
   .observeSingleEvent(of: .value, with: { (snapshot) in
  // Get user value
  if snapshot.exists() == true {
     print("exists")
  }
  else {
     print("does not exist")
  }
}) { (error) in
    print(error.localizedDescription)
}

(Forgive my atrocious Swift syntax; it's not a language I speak yet)

Kato
  • 40,352
  • 6
  • 119
  • 149
0

I was writing out a tidbit of code for you, and then I realized you want Swift, and I use Java :S Anyhow, the conceptual outline should be enough. Create a Firebase Database reference to "users_liked" node, and set a single event value listener to this reference. Next, pass in the datasnapshot to a "foreach" loop swift equivalent, creating a new datasnapshot, "dsChild", for each child of datasnapshot (datasnapshot.getChildren()). Finally check each item by doing dsChild.getValue and utilizing equalTo() to check if value exists. Hope this helps, sorry that I couldn't write it out in Swift !