1

I'm using the .push method on firebase to write new records. I'd like to save the key where the new record is saved to the record itself at the id key. Currently, I do this in 2 operations, first push the record and then update using the ref returned. Can I do this in 1 write? Does it not matter?

anauleau
  • 35
  • 6

2 Answers2

2

If you invoke the Firebase push() method without arguments it is a pure client-side operation.

var newRef = ref.push(); // this does *not* call the server

You can then add the key() of the new ref to your item:

var newItem = {
    name: 'anauleau'
    id: newRef.key()
};

And write the item to the new location:

newRef.set(newItem);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

There's no method to do this in one operation. However, it typically does not matter, because you can always get the push id from the .key() method on the DataSnapshot.

But, there's nothing wrong either about storing the push id. So you coul create a function on the Firebase prototype.

Firebase.prototype.pushWithId = function pushWithid(data) {
  var childRef = this.push();
  data.key = childRef.key();
  childRef.update(data); // or .set() depending on your case
  return childRef;
};

var ref = new Firebase('<my-firebase-app>');
ref.pushWithId({ name: 'Alice' });

Take caution with modifying the prototype of functions you do not own. In this case, you'll likely be fine. This method does little, and there's not much of a chance that the Firebase SDK gains a .pushWithId() method.

David East
  • 31,526
  • 6
  • 67
  • 82