AngularFire 检查是否存在相同标题的项目

AngularFire Check if item of same title exists

我在 /items 中有属性 titlepoints 的 Firebase 条目。在输入新项目之前,我正在尝试检查是否存在相同 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);
      });
    }

});

实时数据库是一个 key/value 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 这意味着你使用的是 0.9 版本的 AngularFire,这不受支持。考虑升级到 Firebase 正式支持的 1.0+ 版本。