【问题标题】:Firebase on('child_added' is adding more unwanted childs / .once returns only the last one in the arrayFirebase on('child_added' 正在添加更多不需要的孩子 / .once 仅返回数组中的最后一个
【发布时间】:2018-01-24 12:28:54
【问题描述】:

处理节点脚本以在提供 json 文件中列出的站点时自动调用 Google 的 pagespeed api。

{
  "1" : "https://bitbucket.org",
  "2" : "https://www.catswhocode.com/blog/"
}

目的是将 api 调用的结果与顶级 url 节点一起添加到 firebase json 数据库,以存储输入的 sitestats 的 firebase 密钥。这是我需要的示例 firebase 数据结构。

sites
 -KrehhWxld7XlKCuFSHRY
   stats { ... }
   url: "https://bitbucket.org"
 -KrehhXAWlYdjAOA9sd95
   stats { ... }
   url: "https://stackoverflow.com"
urls :
 393957be871e209a76e0dc5df1f526ec : -KrehhWxld7XlKCuFSHRY
 7f4c919540be6ec81cd37d9e61da6c37 : -KrehhXAWlYdjAOA9sd95

在承诺中,我正在为 firebase json 数据库中的节点添加参考。

Promise.all(allRes).then( function( values ) {
var ref = db.ref();
var sitesRef = ref.child("sites");
var urlsRef = ref.child("urls");
var psiresults = {};
  SitesArray.map(function (sites, index) {
    psiresults[sites] = values[index]
    desktopStats = values[index].desktopStats;
    mobileStats = values[index].mobileStats;
    sitesRef.push({
      url: sites,
      stats: metricsResponse
    });
    sitesRef.once('child_added', function(snapshot) {
      console.log(snapshot.key) //returns the last key only
    });
  });

当使用once('child_added', ... 时,它只会为最后一项添加到 url 顶级节点。但是,如果 on('child_added', ... 添加相同数据的多个副本和其他子项。每次将子节点添加到 sites 节点时,不确定如何将确切的子键添加到 urls 顶级节点。

【问题讨论】:

  • $uid /urls/$uid/$pid 是什么?是userId
  • 您的意思是 md5 字符串 393957be871e209a76e0dc5df1f526ec?使用站点 url 通过使用 md5 对它们进行散列来创建唯一键。

标签: json node.js firebase firebase-realtime-database promise


【解决方案1】:

如果您想一次性处理所有 URL,请使用 once('value'snapshot.forEach()

sitesRef.once('value', function(snapshot) {
  snapshot.forEach(function(child) {
    console.log(child.key);
  });
});

【讨论】:

  • 如果我使用 'value' 执行此操作,那么我会一次获得所有值,我只想要每次脚本运行时的新条目。但是,'child_added' 只返回最后一个。
  • valuechid_added 没有区别。每次脚本运行时,您都会为所有值触发。这是 Firebase 数据库的标准行为。如果您只想要“新”值,则必须提出“新”的定义(例如,在每个站点中保留一个属性以确定它已被处理,或者保留您最后一个站点的推送 ID已处理)。
【解决方案2】:

最后,我不得不使用..

sitesRef.on('value', function(snapshot) {
  ... 
});

这将返回所有子项,然后我可以根据我的 SitesArray 值过滤结果。我真的不觉得这是一个合适的解决方案,但是,我能够让它发挥作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多