63

I'm attempting to add/remove entries from a Firebase database. I want to list them in a table to be added/modified/removed (front end) but I need a way to uniquely identify each entry in order to modify/remove. Firebase adds a unique identifier by default when using push(), but I didn't see anything referencing how to select this unique identifier in the API documentation. Can this even be done? Should I be using set() instead so I'm creating the unique ID?

I've put this quick example together using their tutorial:

<div id='messagesDiv'></div>
<input type='text' class="td-field" id='nameInput' placeholder='Name'>
<input type='text' class="td-field" id='messageInput' placeholder='Message'>
<input type='text' class="td-field" id='categoryInput' placeholder='Category'>
<input type='text' class="td-field" id='enabledInput' placeholder='Enabled'>
<input type='text' class="td-field" id='approvedInput' placeholder='Approved'>
<input type='Button' class="td-field" id='Submit' Value="Revove" onclick="msgRef.remove()">

<script>
var myDataRef = new Firebase('https://unique.firebase.com/');

  $('.td-field').keypress(function (e) {
    if (e.keyCode == 13) {
      var name     = $('#nameInput').val();
      var text     = $('#messageInput').val();
      var category = $('#categoryInput').val();
      var enabled  = $('#enabledInput').val();
      var approved = $('#approvedInput').val();
      myDataRef.push({name: name, text: text, category: category, enabled: enabled, approved: approved });
      $('#messageInput').val('');
    }
  });
  myDataRef.on('child_added', function(snapshot) {
    var message = snapshot.val();
    displayChatMessage(message.name, message.text, message.category, message.enabled, message.approved);
  });
  function displayChatMessage(name, text, category, enabled, approved, ) {
    $('<div/>').text(text).prepend($('<em/>').text(name+' : '+category +' : '+enabled +' : '+approved+ ' : ' )).appendTo($('#messagesDiv'));
    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
  };
</script>

Now lets assume I have three rows of data:

fred : 1 : 1 : 1 : test message 1
fred : 1 : 1 : 1 : test message 2
fred : 1 : 1 : 1 : test message 3

How do I go about uniquely identifying row 2?

in the Firebase Database they look like this:

-DatabaseName
    -IuxeSuSiNy6xiahCXa0
        approved: "1"
        category: "1"
        enabled: "1"
        name: "Fred"
        text: "test message 1"
    -IuxeTjwWOhV0lyEP5hf
        approved: "1"
        category: "1"
        enabled: "1"
        name: "Fred"
        text: "test message 2"
    -IuxeUWgBMTH4Xk9QADM
        approved: "1"
        category: "1"
        enabled: "1"
        name: "Fred"
        text: "test message 3"
Front_End_Dev
  • 1,205
  • 1
  • 14
  • 24

9 Answers9

67

To anybody finding this question & using Firebase 3+, the way you get auto generated object unique ids after push is by using the key property (not method) on the promise snapshot:

firebase
  .ref('item')
  .push({...})
  .then((snap) => {
     const key = snap.key 
  })

Read more about it in the Firebase docs.

As a side note, those that consider generating their own unique ID should think twice about it. It may have security and performance implications. If you're not sure about it, use Firebase's ID. It contains a timestamp and has some neat security features out of the box.

More about it here:

The unique key generated by push() are ordered by the current time, so the resulting list of items will be chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).

Dan Mindru
  • 5,986
  • 4
  • 28
  • 42
44

To get the "name" of any snapshot (in this case, the ID created by push()) just call name() like this:

var name = snapshot.name();

If you want to get the name that has been auto-generated by push(), you can just call name() on the returned reference, like so:

var newRef = myDataRef.push(...);
var newID = newRef.name();

NOTE: snapshot.name() has been deprecated. See other answers.

redben
  • 5,578
  • 5
  • 47
  • 63
Andrew Lee
  • 10,127
  • 3
  • 46
  • 40
  • This did something, I'm just not sure what... It returns values that look like the unique identifiers but they're different each time I refresh the page. As an example -Iuy2dANtFBZ-OK7I-XK will become -Iuy2dAPFfOkgSy7bLFo then -Iuy2dAPFfOkgSy7bLFp. it changes each line every time I refresh the page. – Front_End_Dev May 19 '13 at 20:33
  • I'm still not sure why but something about your example produced new incorrect keys each time. After some digging I used var message = snapshot.val(); message.id = snapshot.name();. You led me there, if you'd like to update your answer or elaborate as to what may have went wrong, I'd gladly accept your answer. – Front_End_Dev May 20 '13 at 04:58
  • He thought you wanted to get the name of the reference when you were pushing a new chat (i.e. on keypress), as opposed to when you were loading previously saved chats. Does this make sense? – bennlich May 20 '13 at 07:40
  • Thanks! Yes it does, I figured this out around 3-a.m.-ish. I'm now generating my own incremented keys and storing the last key in a config object. It's easier to follow now. – Front_End_Dev May 20 '13 at 16:21
  • hey Front_end_dev how do you set the incremnted keys can you share. – user3722785 Nov 07 '14 at 09:29
  • this is not working for me. the code is asynchronous, how can you get the autoid before it is done on backend? – webduvet Nov 14 '14 at 13:34
  • @Front_End_Dev I have seen that firebase creating the key as it needed. But i have also seen that we can also make our own incremented snapshot key. Can you please let me know, how we can create our own custom incremented snapshot key? – Shreyash Mahajan Jun 08 '15 at 04:25
33

snapshot.name() has been deprecated. use key instead. The key property on any DataSnapshot (except for one which represents the root of a Firebase) will return the key name of the location that generated it. In your example:

myDataRef.on('child_added', function(snapshot) {
    var message = snapshot.val();
    var id = snapshot.key;
    displayChatMessage(message.name, message.text, message.category, message.enabled, message.approved);
});
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
Rima
  • 1,781
  • 14
  • 12
  • 5
    Note that `key` is now a property, not a method on DataSnapshot: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#key – imjared Sep 26 '16 at 18:40
  • @Andrew Lee. Just Curious, as the guy who asked the original question. is it considered bad form to change the accepted answer if the previously accepted answer has been depreciated? What is Stack exchange etiquette here? – Front_End_Dev Jan 30 '17 at 16:55
  • Nothing wrong with changing the accepted answer as far as I know. – Dan Mindru Oct 09 '17 at 09:10
12

To get uniqueID after push() you must use this variant:

// Generate a reference to a new location and add some data using push()
 var newPostRef = postsRef.push();
// Get the unique key generated by push()
var postId = newPostRef.key;

You generate a new Ref when you push() and using .key of this ref you can get uniqueID.

Willem van Ketwich
  • 5,666
  • 7
  • 49
  • 57
Denis Markov
  • 157
  • 1
  • 4
5

As @Rima pointed out, key() is the most straightforward way of getting the ID firebase assigned to your push().

If, however, you wish to cut-out the middle-man, Firebase released a gist with their ID generation code. It's simply a function of the current time, which is how they guarantee uniqueness, even w/o communicating w/ the server.

With that, you can use generateId(obj) and set(obj) to replicate the functionality of push()

Here's the ID function:

/**
 * Fancy ID generator that creates 20-character string identifiers with the following properties:
 *
 * 1. They're based on timestamp so that they sort *after* any existing ids.
 * 2. They contain 72-bits of random data after the timestamp so that IDs won't collide with other clients' IDs.
 * 3. They sort *lexicographically* (so the timestamp is converted to characters that will sort properly).
 * 4. They're monotonically increasing.  Even if you generate more than one in the same timestamp, the
 *    latter ones will sort after the former ones.  We do this by using the previous random bits
 *    but "incrementing" them by 1 (only in the case of a timestamp collision).
 */
generatePushID = (function() {
  // Modeled after base64 web-safe chars, but ordered by ASCII.
  var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';

  // Timestamp of last push, used to prevent local collisions if you push twice in one ms.
  var lastPushTime = 0;

  // We generate 72-bits of randomness which get turned into 12 characters and appended to the
  // timestamp to prevent collisions with other clients.  We store the last characters we
  // generated because in the event of a collision, we'll use those same characters except
  // "incremented" by one.
  var lastRandChars = [];

  return function() {
    var now = new Date().getTime();
    var duplicateTime = (now === lastPushTime);
    lastPushTime = now;

    var timeStampChars = new Array(8);
    for (var i = 7; i >= 0; i--) {
      timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
      // NOTE: Can't use << here because javascript will convert to int and lose the upper bits.
      now = Math.floor(now / 64);
    }
    if (now !== 0) throw new Error('We should have converted the entire timestamp.');

    var id = timeStampChars.join('');

    if (!duplicateTime) {
      for (i = 0; i < 12; i++) {
        lastRandChars[i] = Math.floor(Math.random() * 64);
      }
    } else {
      // If the timestamp hasn't changed since last push, use the same random number, except incremented by 1.
      for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
        lastRandChars[i] = 0;
      }
      lastRandChars[i]++;
    }
    for (i = 0; i < 12; i++) {
      id += PUSH_CHARS.charAt(lastRandChars[i]);
    }
    if(id.length != 20) throw new Error('Length should be 20.');

    return id;
  };
})();
Brandon
  • 7,736
  • 9
  • 47
  • 72
4

You can update record adding the ObjectID using a promise returned by .then() after the .push() with snapshot.key:

const ref = Firebase.database().ref(`/posts`);
ref.push({ title, categories, content, timestamp})
   .then((snapshot) => {
     ref.child(snapshot.key).update({"id": snapshot.key})
   });
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
Lew
  • 350
  • 1
  • 4
  • 11
0

If you want to get the unique key generated by the firebase push() method while or after writing to the database without the need to make another call, here's how you do it:

var reference = firebaseDatabase.ref('your/reference').push()

var uniqueKey = reference.key

reference.set("helllooooo")
.then(() => {

console.log(uniqueKey)



// this uniqueKey will be the same key that was just add/saved to your database



// can check your local console and your database, you will see the same key in both firebase and your local console


})
.catch(err =>

console.log(err)


});

The push() method has a key property which provides the key that was just generated which you can use before, after, or while you write to the database.

chb
  • 1,727
  • 7
  • 25
  • 47
0

Use push() to get a new reference and key to get the the unique id of the it.

var ref = FirebaseDatabase.instance.ref(); 
var newRef = ref.push(); // Get new key
print(newRef.key); // This is the new key i.e IqpDfbI8f7EXABCma1t
newRef.set({"Demo": "Data"}) // Will be set under the above key
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Eslam Sameh Ahmed
  • 3,792
  • 2
  • 24
  • 40
-2

How i did it like:

FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = mFirebaseDatabase.getReference().child("users").child(uid); 

String key = ref.push().getKey(); // this will fetch unique key in advance
ref.child(key).setValue(classObject);

Now you can retain key for further use..

Deepesh
  • 523
  • 4
  • 11