【问题标题】:Firebase: Check for existing before addingFirebase:在添加之前检查是否存在
【发布时间】:2017-11-17 20:07:59
【问题描述】:

我正在使用生成的 ID 添加数据,但正在尝试对“作者”进行分组。

我有一个脚本,它每天根据几个公式将某些人添加到此。我无法知道在任何一天将添加谁,因此我不得不通过让它在提交(推送)时生成密钥然后找到作者密钥并找到具有相同值的其他密钥来构建数据库。

我遇到的问题是在添加新记录之前检查值是否存在。关键值之一是“URL”。我试图写一些东西来检查每条记录的值,但它似乎重复并写入数据库,不管值是什么,即使我可以正确检测到重复。

function CheckDupes(newUrl, author, title, score, url, certified, date){
  var stories = [];
  var duped = "false";

  var leadsRef = database.ref().child("Authors").once("value").then(function(authorSnapshot)
  {
    authorSnapshot.forEach(function(child) {
        stories.push(child.val());
      });
    for(var i = 0; i < stories.length; i++)
    {
      console.log("Story: " + stories[i].url);
      if(stories[i].url == newUrl)
      {
        console.log("Duplicate - " + stories[i].url);
        duped = "true";
        alert("Story Exists!");
        break;
      }
    }
  });

  console.log(duped);
  if(duped == "false")
  {
    firebase.database().ref('Authors/').push({
      author: author,
      title: title,
      score: score,
      url: url,
      certified: certified,
      date: date
    });
    alert("Story has been added!");
  }

这是我目前拥有的。它会找到重复的,但无论是否找到它都会添加到数据库中。我已将检查移到 foreach 循环之外,但它根本不存储任何内容。

【问题讨论】:

    标签: javascript firebase firebase-realtime-database nosql


    【解决方案1】:
    function CheckDupes(newUrl, author, title, score, url, certified, date){
      var stories = [];
      var duped = "false";
      var leadsRef = database.ref().child("Authors").once("value").then(function(authorSnapshot)
      {
        authorSnapshot.forEach(function(child) {
            stories.push(child.val());
            count++;
          });
          for(var i = 0; i < stories.length; i++)
          {
            if(stories[i].url == newUrl)
            {
              duped = "true";
              alert("Story Exists!");
              return;
              break;
            }
          }
          if(duped == "false")
          {
            firebase.database().ref('Authors/').push({
              author: author,
              title: title,
              score: score,
              url: url,
              certified: certified,
              date: date
            });
            alert("Story has been added!");
          }
      });
    

    需要 authorSnapshot 函数中的所有内容。愚蠢的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      相关资源
      最近更新 更多