如何获取通过“推送”添加到 Firebase 的新帖子的 ID

How to get the id of a new post that was added to Firebase with `push`?

本文关键字:添加 Firebase 推送 新帖 ID 何获取 获取      更新时间:2023-09-26

我正在尝试为帖子创建一个喜欢/不喜欢的投票系统。首先,我使用 .push 向 Firebase 发送文本输入:

$('.btn').click(function(){
  var post = $('.status-box').val();
  var id = snapdata;
  ref.child("post").push({user: id, text: post});
  $('.status-box').val('');
});

对于我想为已经存在的帖子添加值的每个"喜欢",问题是我不知道如何访问.push为每个帖子生成的 id。

正如 Dan 已经说过的,push 方法返回对新节点的引用。从那里您可以轻松获得密钥:

var newPost = ref.child("post").push({user: id, text: post});
console.log('The new post is under key: ', newPost.key());

调用.push将返回对您传递给它的数据的 Firebase 引用。

返回值

Firebase
生成的地理位置的 Firebase 参考。

https://www.firebase.com/docs/web/api/firebase/push.html

所以理论上你不应该需要生成的id,因为你有它指向的引用。