为什么一个代码从Firebase给我正确的密钥,而另一个却没有?

时间:2020-08-01 01:36:57

标签: javascript firebase firebase-realtime-database

我一直在研究一个简单的卡片目录项目,该项目从表单中获取输入并将其显示在卡片上。

在每张卡上,可以选择完全删除卡或选中/取消选中一个框。为此,我需要访问Firebase实时数据库中的对象。

每个对象都是由.push()创建的,并生成一个随机键名,我想访问该键名以更改或删除该对象。

我在https://firebase.google.com/docs/database/web/read-and-write上阅读了文档,它提供了一种在推送之前获取密钥的方法。在提供的示例中使用update()可以正常工作,但是当我在push()上尝试使用时,键不匹配。

此外,由于我需要在呈现卡片的单独函数中使用密钥,因此我尝试将其设置为全局变量并返回undefined

您能告诉我如何获取用于其他功能的密钥吗?

谢谢!

当我在此处的函数内进行console.log newPostKey时,它与数据库中的内容匹配,但是当我在外部函数中进行操作时,我得到了undefined

var database = firebase.database();
let newPostKey;

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;
  console.log(newPostKey);

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

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

writeNewPost("zzz", "drew", "bucolic", "bobross", "beardo");
console.log(newPostKey);

这返回的newPostKey与我在Firebase中看到的不匹配。外面也是不确定的。

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

  var newPostKey = firebase.database().ref().child('posts').push().key;

  console.log(newPostKey);

  return firebase.database().ref().child('posts').push(postData);
};
writeNewPost("zzz", "drew", "bucolic", "bobross", "beardo");
console.log(newPostKey);

1 个答案:

答案 0 :(得分:1)

每次在引用上调用push时,都会生成一个新密钥。由于您在第二个片段中两次调用了push(),因此您正在生成两个密钥。

您更有可能这样做:

var newPostKey;
function writeNewPost(uid, username, picture, title, body) {
  var postData = {
    author: username,
    uid: uid,
    body: body,
    title: title,
    starCount: 0,
    authorPic: picture
  };

  newPostKey = firebase.database().ref().child('posts').push().key;

  console.log(newPostKey);

  return firebase.database().ref().child('posts').child(newPostKey).set(postData);
};
writeNewPost("zzz", "drew", "bucolic", "bobross", "beardo");
console.log(newPostKey);

因此,通过使用.child(newPostKey).set(postData)而不是push(postData),数据将被添加到newPostKey子级,而不是新密钥。


由于您还可以从push返回的DatabaseReference获取密钥,因此该代码段也可以写为:

function writeNewPost(uid, username, picture, title, body) {
  return firebase.database().ref().child('posts').push({
    author: username,
    uid: uid,
    body: body,
    title: title,
    starCount: 0,
    authorPic: picture
  });
};
let ref = writeNewPost("zzz", "drew", "bucolic", "bobross", "beardo");
console.log(ref.key);
相关问题