0

I have this database structure with an array of pending friend requests:

data in Firebase

The green represents the value that I want to search for.

Now I would like to do some simple checking to see if a person has already sent a friend request to a person, without grabbing the data first and then looping through it, which would take a hit at performance.

I looked at this snippet which queries for users:

https://gist.github.com/anantn/4323949

And I tweaked it for my scenario and made it a bit more generic so that I can query whatever I'd like to easily, this function lives inside a factory called globals:

searchFirebase: function(data, endpoint) {

  var dataExists;

  function dataExistsCallback(data, exists) {

    if (exists) {
      dataExists = false;
    } else {
      dataExists = true;
    }
  }

  function checkIfDataExists(data) {

    // fbRefs.getReference returns new Firebase('https://mydb.firebaseio.com/somepath') for example
    var ref = fbRefs.getReference(endpoint);

    ref.child(data).once('value', function(snapshot) {

      var exists = (snapshot.val() !== null);

      dataExistsCallback(data, exists);
    });
  }

  checkIfDataExists(data);

  return dataExists;
}

From my controller:

var path = 'users/' + $routeParams.id + '/profile/friendslist/pending';
var uuid = 'facebook:1230928984398439'; // Example uuid to query for

console.log(globals.searchFirebase(uuid, path));

The problem is that the searchFirebase function always returns true, no matter what data I pass into it.

I want to be able to pass a string which is tested against a bunch of object's properties to see if the value exists.

Have I made any obvious mistakes here which causes it to always return true?

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Frank van Puffelen Sep 06 '15 at 15:21
  • @FrankvanPuffelen Shouldn't it return undefined then and not true? – Chrillewoodz Sep 06 '15 at 17:45
  • 1
    Regardless, Firebase calls are asynchronous. You either need to supply a callback to `searchFirebase` or use promises. Your searching method also won't work. You should look into [`orderByChild`](https://www.firebase.com/docs/web/api/query/orderbychild.html) and combine with [`equalTo`](https://www.firebase.com/docs/web/api/query/equalto.html). – Anid Monsur Sep 06 '15 at 21:50

0 Answers0