Search code examples
javascriptfirebasereact-nativegoogle-cloud-firestorereact-native-firebase

Firebase array-contains - search through the values not the keys


How do you query for a value in an array that has a numeric keyset?

For example this query does not work because I believe it is looking at the indexing rather then the values:

var db = firebase.firestore();
var users = db.collection("Users");
var currentUser = firebase.auth().currentUser;
var result = users.where('liked', 'array-contains', currentUser.uid);
if (result.length > 0) {
  return 'You have a match!';
} else {
  return 'No matches';
}

enter image description here


Solution

  • As Stratubas commented, the problem is in this code:

    var result = users.where('liked', 'array-contains', currentUser.uid);
    

    This code constructs a query, but does not yet execute the query. So result is a Query object. To execute the query, and get the results from the server, you call get() on the query, which then returns a Promise<QuerySnapshot>. Once the promise results, you can handle the results in the QuerySnapshot object.

    var query = users.where('liked', 'array-contains', currentUser.uid);
    query.get().then(function(querySnapshot) {
      if (querySnapshot.size > 0) {
        console.log('You have a match!');
      } else {
        console.log('No matches');
      }
    });
    

    In more modern JavaScript, the above can also be written as:

    let query = users.where('liked', 'array-contains', currentUser.uid);
    let querySnapshot = await query.get()
    if (querySnapshot.size > 0) {
      console.log('You have a match!');
    } else {
      console.log('No matches');
    }