【问题标题】:AngularFire Check if item of same title existsAngularFire 检查是否存在同名项目
【发布时间】:2016-02-26 08:11:57
【问题描述】:

我在 /items 中有 Firebase 条目,属性为 titlepoints。我正在尝试在输入新项目之前检查是否存在相同的 title 项目。

这是我所拥有的,但它没有发生:

app.controller('ItemController', function($scope, FURL, $firebase, $location, toaster) {

  var ref = new Firebase(FURL);
  var fbItems = $firebase(ref.child('items')).$asArray();

  $scope.addItem = function(item) { 

    // var iItem = $scope.item.title;

    var userId = $scope.item.title;
      checkIfUserExists(userId);
        };

    function userExistsCallback(userId, exists) {
      if (exists) {
        alert('user ' + userId + ' exists!');
      } else {
        alert('user ' + userId + ' does not exist!');
      }
    }

    function checkIfUserExists(userId) {
      ref.child('items').once('value', function(snapshot) {
        var exists = (snapshot.val() !== null);
        userExistsCallback(userId, exists);
      });
    }

});

【问题讨论】:

    标签: javascript angularjs firebase angularfire firebase-security


    【解决方案1】:

    实时数据库是一个键/值 JSON 数据库。这意味着如果您将标题名称存储为键,查找它会非常快。

    以下面的数据为例。

    {
      "items": {
        "title-1": {
           "something": "foo"
        },
        "title-2": {
           "something": "baz"
        }
      }
    }
    

    现在假设我们要检查title-2 是否存在。我们可以通过简单的阅读来做到这一点。

    function checkForTitle(title, cb) {
      var itemsRef = new Firebase('<my-firebase-app>/items');
      var titleRef = itemRef.chld(title).once('value', function(snap) {
         cb(snap.exists());
      });
    }
    
    checkForTitle('title-2', function(doesExist) {
      console.log(doesExist); // true
    });
    

    为确保检查发生在服务器上,您可以为其编写安全规则。或者,最好使用新的 Bolt Compiler

    {
      "items": {
         "$item": {
           ".write": "!data.exists()" // don't overwrite existing data
         }
       }
    }
    

    您应该升级您的 AngularFire 版本。我注意到您使用的是 $firebase().$asArray,这意味着您使用的是 AngularFire 的 0.9 版本,这是不受支持的。考虑升级到 Firebase 官方支持的 1.0+ 版本。

    【讨论】:

    • 很抱歉成为 AngularFire 的小伙伴,但我将如何以标题名称作为密钥保存我的项目?
    • 这取决于你在做什么。您可能不需要 AngularFire,只需使用带有 ref.child('title-2').set({ title: 'title-2' }); 的 Firebase SDK。 AngularFire 是用来同步数据的,保存数据并不总是需要下载。
    • 谢谢。目前我认为不需要同步数据。
    • 稍作调整后就像魅力一样工作。谢谢。即使情况不同,有什么方法可以找到物品吗?现在如果情况不同,它不会注册相同的。
    猜你喜欢
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2018-11-18
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多