Steven Rolls
Steven Rolls

Reputation: 23

AngularFire Check if item of same title exists

I have Firebase entries in /items with the properties title and points. I am trying to check to see if an item of the same title exists before entering a new one.

This is what I have but it does not happen:

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);
      });
    }

});

Upvotes: 2

Views: 337

Answers (1)

David East
David East

Reputation: 32604

The Realtime Database is a key/value JSON database. This means that if you store a title name as a key, it will be super quick to look it up.

Take the following data for example.

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

Now let's say we want to check to see if title-2 exists. We can do this with an easy read.

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
});

To make sure the check happens on the server, you can write a Security Rule for it. Or, better yet use the new Bolt Compiler.

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

You should upgrade your AngularFire version. I noticed you're using $firebase().$asArray which means you're on the 0.9 version of AngularFire, which is unsupported. Look into upgrading to the 1.0+ version which is officially support by Firebase.

Upvotes: 1

Related Questions