javascriptfirebasereact-nativegoogle-cloud-firestoregeofirestore

Initial Query.orderBy() Parameter has to be the same as the Query.where() fieldPath parameter(s) when an inequality operator is invoked


I have this code where I am trying to fetch a document from a collection where time is not older than half an hour ago. It fails exactly in the inequality operator.

try {
  const HALF_HOUR = 0.1 * 6000 * 6000 / 2;
  const tsToMillis = firebase.firestore.Timestamp.now().toMillis();
  const currenttime = new Date(tsToMillis - HALF_HOUR);

  const myCurrentLoc = location[0]; // my device location
  const latitude = myCurrentLoc.latitude;
  const longitude = myCurrentLoc.longitude;

  const geocollection = GeoFirestore.collection('chats');
  const query = await geocollection.limit(1).near({ center: new firebase.firestore.GeoPoint(latitude, longitude), radius: 0.03 });
  query.where('details.time', '>=', currenttime).get().then((querySnapshot) => {
    if (!querySnapshot.empty) {
      querySnapshot.docs.forEach(documentSnapshot => {
        if (documentSnapshot.exists) {
          this.fetchAllMessages(documentSnapshot.id);
        }
      });
    }
  }).catch(error => {
    console.error("Error in fetch_messages", error);
  });
} catch (e) {
  console.error("Something happened: ", e); // ERROR IS TRIGGERED HERE
}

C:\MyProjects\BLEConnect\node_modules\react-native\Libraries\Core\ExceptionsManager.js:180 Something happened: Error: firebase.firestore().collection().orderBy() Invalid query. Initial Query.orderBy() parameter: g.geohash has to be the same as the Query.where() fieldPath parameter(s): details.time when an inequality operator is invoked

This error occurred only when invoking inequality operator but not "==" equal operator. Why so? I simply dont get it.

P.S.: the "time" field is added when the geohash has been created, so in the same query:

const tsToMillis = firebase.firestore.Timestamp.now().toMillis();
const currenttime = new Date(tsToMillis);
const geocollection = GeoFirestore.collection('chats');
geocollection.add({
  name: 'Geofirestore',
  uid: device_id,    
  coordinates: new firebase.firestore.GeoPoint(latitude, longitude),
  time: currenttime
})

Solution

  • From the Firestore documentation on query limitations:

    In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons must all filter on the same field.

    The way the inequality operators are implemented requires that you order on that field first. For the equality operator Firestore is able to do more on its own, for example combining information from multiple indexes in a so-called zig-zag-merge-join.