Skip to content Skip to sidebar Skip to footer

Firebase: Can I Combine A Push With A Multi-location Update?

I need to create a new object with a generated key and update some other locations, and it should be atomic. Is there some way to do a push with a multi-location update, or do I ha

Solution 1:

There are two ways to invoke push in Firebase's JavaScript SDK.

  1. using push(newObject). This will generate a new push id and write the data at the location with that id.

  2. using push(). This will generate a new push id and return a reference to the location with that id. This is a pure client-side operation.

Knowing #2, you can easily get a new push id client-side with:

var newKey = ref.push().key(); // on newer versions ref.push().key;

You can then use this key in your multi-location update.

Solution 2:

I'm posting this to save some of future readers' time.

Frank van Puffelen 's answer (many many thanks to this guy!) uses key(), but it should be key.

key() throws TypeError: ref.push(...).key is not a function.

Also note that key gives the last part of a path, so the actual ref that you get it from is irrelevant.

Here is a generic example:

varref = firebase.database().ref('this/is/irrelevant')

var key1 = ref.push().key // L33TP4THabcabcabcabcvar key2 = ref.push().key // L33TP4THxyzxyzxyzxyzvar updates = {};
updates['path1/'+key1] = 'value1'
updates['path2/'+key2] = 'value2'ref.update(updates);

that would create this:

{
  'path1':
  {
    'L33TP4THabcabcabcabc': 'value1'
  },
  'path2':
  {
    'L33TP4THxyzxyzxyzxyz': 'value2'
  }
}

I'm new to firebase, please correct me if I'm wrong.

Post a Comment for "Firebase: Can I Combine A Push With A Multi-location Update?"