【问题标题】:Write pre-determined node id when pushing to Firebase array推送到 Firebase 数组时写入预先确定的节点 ID
【发布时间】:2017-11-09 15:55:24
【问题描述】:

以前有人问过这个问题,但提供的解决方案似乎都没有解决我的问题:

我在 Firebase 上有一组数据,我使用“for”循环和索引值循环遍历这些数据以在我的应用中生成内容。这适用于预先确定的数据集,因为 ID 是简单的数组数字,但是当用户添加一些新数据(使用 push() 添加到数组中时,firebase 会创建一个唯一的节点键(例如 -KyWRU7RRCE_V1w_OiZx)新的数据集由于某种原因阻止了我的循环工作(控制台中没有显示错误)。

如果我去 firebase 并手动确保新数据集具有数值,循环将再次开始工作。如何使当用户将新数据推送到数组时,生成的键是数字?我试过这个:

  // Push new routine to Firebase.
  var firebaseRef = firebase.database().ref();
  var createdExercise = JSON.parse(localStorage.newRoutine);
  $("#save").click(function()
  {
    firebaseRef.child("workouts").key(some_indexed_value).push(createdExercise);
  });

但控制台返回以下错误:Uncaught TypeError: firebaseRef.child(...).key is not a function。

如果有用,这里是我正在使用的循环:

// Initialize Firebase.
firebase.initializeApp(config);
// Reference data.
var dbRef = firebase.database().ref().child("workouts");
// Sync with Firebase in real time.
dbRef.on("value", snap =>
{
  var workouts = snap.val();

  for (var i = 0; i < workouts.length; i++)
  {
    var routine = workouts[i].title;
    var time = 3;
    var exercises = workouts[i].exercises;
    var icons;

    $("#cardList").append(createCards(routine));
  }
});

还有一张我在 Firebase 上的 JSON 数据图片:

【问题讨论】:

    标签: javascript arrays loops firebase firebase-realtime-database


    【解决方案1】:

    您的问题的答案是像这样使用.set() 而不是.push()

    firebaseRef.child("workouts").child(some_indexed_value).set(createdExercise);
    

    这将使用您的自定义键在锻炼下创建一个节点。

    但建议使用push keys 和使用forEach() 方法得到结果,而不是使用for loop

    【讨论】:

    • 超级!非常感谢。
    猜你喜欢
    • 2016-12-08
    • 2015-01-22
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2019-04-16
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多