简体   繁体   English

Firebase on('child_added'正在添加更多不需要的孩子/.once仅返回数组中的最后一个

[英]Firebase on('child_added' is adding more unwanted childs / .once returns only the last one in the array

Working on a node script to automatically call Google's pagespeed api upon giving the sites listed in a json file. 在提供json文件中列出的站点后,使用节点脚本来自动调用Google的pagespeed api。

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

The aim is to add the results for the api call to firebase json database along with a top-level url node to store the firebase key for the sitestats entered. 目的是将api调用的结果与顶级url节点一起添加到firebase json数据库中,以存储输入的sitestats的firebase密钥。 Here is example firebase data structure I need. 这是我需要的示例Firebase数据结构。

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

Within a promise I am adding a reference for the nodes in firebase json database. 在承诺中,我正在为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
    });
  });

When using once('child_added', ... it adds to the url top level node only for the very last item. However, if on('child_added', ... multiple copies of the same data and other childs are added. Not sure how to add the exact child key to the urls top level node when a child is added to sites node each time. 当使用once('child_added', ... ,仅将最后一项添加到url顶级节点。但是,如果on('child_added', ...则添加相同数据的多个副本和其他子项。每次将子项添加到站点节点时,不确定如何将确切的子项添加到urls顶级节点。

If you want to process all URLs once, use once('value' with snapshot.forEach() : 如果要一次处理所有URL,请使用once('value'snapshot.forEach()

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

Finally, I had to do it using.. 最后,我不得不使用..

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

This returns all the children and then I am able to filter the result based on my SitesArray values. 这将返回所有子项,然后我可以根据我的SitesArray值过滤结果。 I don't really find this an appropriate solution, however, I was able to make it work. 我真的没有找到合适的解决方案,但是,我能够使它起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM