In Firebase when using push() How do I pull the unique ID

JavascriptJqueryFirebase

Javascript Problem Overview


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"

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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);
});

Solution 4 - Javascript

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.

Solution 5 - Javascript

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;
  };
})();

Solution 6 - Javascript

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})
   });

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFront_End_DevView Question on Stackoverflow
Solution 1 - JavascriptDan MindruView Answer on Stackoverflow
Solution 2 - JavascriptAndrew LeeView Answer on Stackoverflow
Solution 3 - JavascriptRimaView Answer on Stackoverflow
Solution 4 - JavascriptDenis MarkovView Answer on Stackoverflow
Solution 5 - JavascriptBrandonView Answer on Stackoverflow
Solution 6 - JavascriptLewView Answer on Stackoverflow
Solution 7 - JavascriptAbdulmohsen AlabraView Answer on Stackoverflow
Solution 8 - JavascriptEslam Sameh AhmedView Answer on Stackoverflow
Solution 9 - JavascriptDeepeshView Answer on Stackoverflow