Xin Cheng
Xin Cheng

Reputation: 69

SWIFT - Firebase database - Add a key and a value to every user

Currently I have an existing database with example below:

enter image description here

Now I want to add a new key (say -counts: "") cause I have a new function in app. Is there a function I can add /counts: "" to all users?

I know how to add a key and value to one user:

let uid = Auth.auth().currentUser?.uid
let dict = ["dob": ""] as [String : Any]
    REF_CURRENT_USER.updateChildValues(dict as [AnyHashable : Any], withCompletionBlock: { (error, ref) in
        if error != nil {

        } else {

        }

    })

But I have no idea how to add a key and a value to every existing user without manually adding it in the database.

Upvotes: 0

Views: 324

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

You can only write/add a value if you know the exact path to the location of that value. So to add a property to each user, you'd:

  1. Load all users (so the /Users node).
  2. Loop over all child nodes in that snapshot.
  3. Call updateChildNodes() or setValue() on the reference to that child snapshot, e.g. childSnapshot.ref.child("counts").setValue(42).

Upvotes: 3

Related Questions