3

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 have to use the old transaction method? This applies for any client platform, but here's an example in JavaScript.

var newData = {};
newData['/users/' + uid + '/last_update'] = Firebase.ServerValue.TIMESTAMP;
newData['/notes/' + /* NEW KEY ??? */] = {
  user: uid,
  ...
};
ref.update(newData);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Travis Christian
  • 2,412
  • 2
  • 24
  • 41

2 Answers2

12

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • How to use this key? Suppose I have a button that counts clicks on it. Firebase data have a variable (click_count=21). So, if someone clicks button, it gets created new ID because i am using first method. Can i have something like that key, so that whatever i add, it stores it in same key. Even if i refresh webpage. – rupinderjeet Apr 25 '16 at 15:16
  • Thanks for the very helpful reminder that push() is a client-side operation! – Lucy Apr 18 '17 at 02:50
  • Thanks for the note that it is a client side operation. Dart/Flutter's worked the same way. – Phuah Yee Keat May 26 '18 at 00:12
0

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:

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

var key1 = ref.push().key // L33TP4THabcabcabcabc
var key2 = ref.push().key // L33TP4THxyzxyzxyzxyz

var 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.

Stratubas
  • 2,939
  • 1
  • 13
  • 18