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

2020-01-26 23:55发布

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"

8条回答
地球回转人心会变
2楼-- · 2020-01-27 00:30

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.

查看更多
够拽才男人
3楼-- · 2020-01-27 00:32

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.

查看更多
The star\"
4楼-- · 2020-01-27 00:32

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

查看更多
仙女界的扛把子
5楼-- · 2020-01-27 00:39

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);
});
查看更多
Lonely孤独者°
6楼-- · 2020-01-27 00:41

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})
   });
查看更多
Animai°情兽
7楼-- · 2020-01-27 00:54

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

查看更多
登录 后发表回答