【问题标题】:How do I to target a single value in firebase database?如何在 firebase 数据库中定位单个值?
【发布时间】:2016-08-28 21:05:10
【问题描述】:

我无法确定如何定位 firebase 数据库中的单个对象。例如,我希望在单击索引卡时显示特定的单词/定义。我正在使用它来存储数据:

wordVal = $("#word").val();
defVal = $("#def").val();

data = firebase.database().ref("indexCards");
data.push( { 'word': wordVal, 'definition': defVal } );         

这个来检索它:

data.on("child_added", function(snapshot){
    console.log(snapshot.val().word);   
    console.log(snapshot.val().definition);
});

这给了我完整的单词和定义列表。我想分别引用特定的词和特定的定义。文档说我可以通过这样做来引用特定值 - firebase.database().ref("child/path")

但我的问题是......当父母是那些随机数字和字母时,我如何引用路径(见下文)?我知道这些是由 firebase 生成的唯一 ID,但我不知道如何访问它们,就像访问普通对象一样。

{
  "-KQIOHLNsruyrrnAhqis" : {
    "definition" : "person, place, thing",
    "word" : "noun"
  },
  "-KQIOO7Wtp2d5v2VorqL" : {
    "definition" : "device for photos",
    "word" : "camera"
  },
  "-KQISp4WMnjABxQayToD" : {
    "definition" : "circus act",
    "word" : "clown"
  },
  "-KQITC9W1lapBkMyiL7n" : {
    "definition" : "device used for cutting",
    "word" : "scissors"
  }
}

【问题讨论】:

  • 您在问题中包含了 JSON 树的图片。请将其替换为实际的 JSON 作为文本,您可以通过单击 Firebase 数据库控制台中的导出按钮轻松获取该文本。将 JSON 作为文本使其可搜索,让我们可以轻松地使用它来测试您的实际数据并在我们的答案中使用它,一般来说这只是一件好事。
  • @FrankvanPuffelen 没问题,我只是添加了 JSON 文本

标签: javascript firebase firebase-realtime-database


【解决方案1】:

您可以使用这样的查询:

data = firebase.database().ref('indexCards').orderByChild('word').equalTo('noun')

不言自明,我们得到 indexCards 的引用,其中键 word 的值等于 noun,因此它将返回带有键 -KQHZ3xCHTQjuTvonSwj 的对象/em>

链接到Firebase docs: Retrieve data - Sorting and Filtering data

【讨论】:

    【解决方案2】:

    您需要将初始 push 放入一个对象中,然后稍后再调用该对象。即

    推送数据: firebase.database().ref().push( { 'word': wordVal, 'definition': defVal } )

    要更新数据或稍后调用它: firebase.database().ref("indexCards").set({})

    或者在这种情况下: 数据集({})

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2019-05-24
      • 2020-06-19
      • 2018-08-21
      • 2018-02-11
      相关资源
      最近更新 更多