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

新手上路,请多包涵

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

错误是“ReferenceError:ref 未定义”

原文由 komal deep singh chahal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 371
2 个回答

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

在 Firebase 的 JavaScript SDK 中有两种调用 push 的方法。

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

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

知道#2,你可以很容易地获得一个新的推送 ID 客户端:

>  var newKey = ref.push().key();
>
> ```
>
> 然后,您可以在多位置更新中使用此密钥。

[https://stackoverflow.com/a/36774761/2305342](https://stackoverflow.com/a/36774761/2305342)

> 如果您在不带参数的情况下调用 Firebase `push()` 方法,则它是纯客户端操作。
>
> ```
>  var newRef = ref.push(); // this does *not* call the server
>
> ```
>
> 然后,您可以将新参考的 `key()` 添加到您的项目:
>
> ```
>  var newItem = {
>     name: 'anauleau'
>     id: newRef.key()
> };
>
> ```
>
> 并将项目写入新位置:
>
> ```
>  newRef.set(newItem);
>
> ```

[https://stackoverflow.com/a/34437786/2305342](https://stackoverflow.com/a/34437786/2305342)

在你的情况下:

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

}

”`

原文由 iOSGeek 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 Ronnie Royston 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题