Search code examples
firebasefirebase-realtime-databasefirebase-cli

Update item in each node of a collection in a Realtime Database using Firebase CLI


We've got a collection of profiles in a Firebase Realtime Database that we'd like to update. The structure is simple

/profiles

  • abc { key1: value, key2: value }
  • deg { key1: value, key2: value }
  • xyz { key1: value, key2: value }

Each item is an object with some key/value pairs and we'd like to add a new key/value pair to all items in the collection (approx 5000 of them) so that:

  • abc { key1: value, key2: value, key3: value }
  • deg { key1: value, key2: value, key3: value }
  • xyz { key1: value, key2: value, key3: value }

Is there a way to do this using the Firebase CLI database:push or database:set methods?

Thank you


Solution

  • To be able to update an item in the database, you must know the full path to that item. So to update all child nodes of a location, you'll need to:

    1. read the data at that location
    2. iterate over the child nodes
    3. update each child node

    There is no built-in single operation for this in the Firebase CLI, although you can compose it by combining the datbase:get and database:update commands, with a custom script that iterates over the child nodes.

    I personally prefer to do these in regular code though, since it's quite easy to write such an update loop in JavaScript (so that it can run in a browser, or on Node.js). See for an example, my answer here: Update all child in Firebase.