在Firebase中使用push()时如何在数据库中获取唯一ID和存储

kom*_*hal 34 javascript firebase reactjs firebase-realtime-database

我在firebase中推送数据,但我想在我的数据库中存储唯一的id.有人可以告诉我,如何推送具有唯一ID的数据.

我是这样想的

  writeUserData() {
    var key= ref.push().key();
    var newData={
        id: key,
        websiteName: this.webname.value,
        username: this.username.value,
        password : this.password.value,
        websiteLink : this.weblink.value
    }
    firebase.database().ref().push(newData);
  }
Run Code Online (Sandbox Code Playgroud)

错误是"ReferenceError:ref未定义"

iOS*_*eek 53

您可以使用key()任何ref对象的函数来获取密钥

push在Firebase的JavaScript SDK中有两种方法可以调用.

  1. 使用push(newObject).这将生成一个新的推送ID并在具有该ID的位置写入数据.

  2. 使用push().这将生成一个新的推送ID并返回对具有该ID的位置的引用.这是一个纯粹的客户端操作.

知道#2,您可以轻松获得一个新的推送ID客户端:

var newKey = ref.push().key();
Run Code Online (Sandbox Code Playgroud)

然后,您可以在多位置更新中使用此密钥.

/sf/answers/2574233301/

如果在push()没有参数的情况下调用Firebase 方法,则它是纯客户端操作.

var newRef = ref.push(); // this does *not* call the server
Run Code Online (Sandbox Code Playgroud)

然后,您可以将key()新参考添加到您的项目:

var newItem = {
    name: 'anauleau'
    id: newRef.key()
};
Run Code Online (Sandbox Code Playgroud)

并将项目写入新位置:

newRef.set(newItem);
Run Code Online (Sandbox Code Playgroud)

/sf/answers/2410645051/

在你的情况下:

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

}
Run Code Online (Sandbox Code Playgroud)

  • 我不得不替换ref.push().key(); 用ref.push().key; 看起来你需要获得一个属性而不是调用一个函数. (11认同)
  • 它给出错误"键未定义". (2认同)

Ron*_*ton 27

Firebase v3保存数据

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我花了一段时间才意识到为什么我的代码不起作用,然后我注意到了`key;`在你的精彩答案中 - 我使用的是`key();`,就像在v2中一样. (5认同)
  • 请参阅[获取push()生成的唯一密钥](https://firebase.google.com/docs/database/admin/save-data#g​​etting-the-unique-key-generated-by-push) (3认同)

Aza*_*lvi 6

您可以像这样使用 Promise 获取最后插入的项目 ID

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));
Run Code Online (Sandbox Code Playgroud)