如何获取使用`push`添加到Firebase的新帖子的ID?

时间:2015-01-25 20:33:08

标签: javascript firebase voting-system

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

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

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

2 个答案:

答案 0 :(得分:2)

正如Dan所说,push方法返回对新节点的引用。从那里你可以轻松获得钥匙:

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

答案 1 :(得分:1)

致电.push会返回Firebase对您传递给它的数据的引用。

  

返回值

     

火力地堡
  生成位置的Firebase参考。

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

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