In Firebase when using push() How do I get the unique ID and store in my database

冷暖自知 提交于 2019-11-27 03:21:15
iOSGeek

You can get the key by using the function key() of any ref object

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

You can then use this key in your multi-location update.

https://stackoverflow.com/a/36774761/2305342

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

https://stackoverflow.com/a/34437786/2305342

in your case :

writeUserData() {
  var myRef = firebase.database().ref().push();
  var key = myRef.key();

  var newData={
      id: key,
      Website_Name: this.web_name.value,
      Username: this.username.value,
      Password : this.password.value,
      website_link : this.web_link.value
   }

   myRef.push(newData);

}

Firebase v3 Saving Data

function writeNewPost(uid, username, picture, title, body) {
  // A post entry.
  var postData = {
    author: username,
    uid: uid,
    body: body,
    title: title,
    starCount: 0,
    authorPic: picture
  };

  // Get a key for a new Post.
  var newPostKey = firebase.database().ref().child('posts').push().key;

  // Write the new post's data simultaneously in the posts list and the user's post list.
  var updates = {};
  updates['/posts/' + newPostKey] = postData;
  updates['/user-posts/' + uid + '/' + newPostKey] = postData;

  return firebase.database().ref().update(updates);
}

You can get last inserted item id using Promise like this

let postRef = firebase.database().ref('/post');
postRef.push({ 'name': 'Test Value' })
    .then(res => {
        console.log(res.getKey()) // this will return you ID
    })
    .catch(error => console.log(error));

It looks like now .push() always returns an Observable. When applied the solutions above I had the following error: "Type 'String' has no compatible call signatures".

That being said, I refer what did work in my case for this new version:

Type 'String' has no compatible call signatures

This worked for me:

 var insertData = firebase.database().ref().push(newData);
 var insertedKey = insertData.getKey(); // last inserted key

See Here: Saving data with firebase.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!