1

I want to keep track of different programmatically created Firestore queries in a web app so I know when to search on the database and when to use a cache. The problem is I can't seem to get any two queries to compare to each other successfully.

let query1 = myCol
    .where("someProp", "==", false)
    .where("someOtherProp", "==", "something else")
    .orderBy("propX")
    ;
let query2 = myCol
    .where("someProp", "==", true)
    .where("someOtherProp", "==", "something")
    .orderBy("propY")
    ;

console.log("haveSameProperties(query1, query2) ", haveSameProperties(query1, query2)); //prints true
console.log("query1.toString()==query2.toString()", (query1.toString()==query2.toString())); //prints true
console.log("areDataObjectsEqual(query1, query2)", areDataObjectsEqual(query1, query2)); //type error

Where my util functions are:

export function haveSameProperties(obj1, obj2) {
    const obj1Length = Object.keys(obj1).length;
    const obj2Length = Object.keys(obj2).length;
    if(obj1Length === obj2Length) {
        return Object.keys(obj1).every(
            key => obj2.hasOwnProperty(key));
    }
    return false;
}

export function areDataObjectsEqual(obj1, obj2) {
    return JSON.stringify(obj1) === JSON.stringify(obj2);
}

How can I save and compare Firestore queries in Javascript?

Mr.Drew
  • 939
  • 2
  • 9
  • 30
  • can show what was type error? looks like its unable to cast to string. – Rafee Jan 18 '21 at 06:54
  • I believe the issue you are facing has to do with the way JS handles comparisons. There is plenty information online about this [1](https://medium.com/javascript-in-plain-english/comparing-objects-in-javascript-ce2dc1f3de7f), [2](https://dmitripavlutin.com/how-to-compare-objects-in-javascript/), [3](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects). – Daniel Ocando Jan 18 '21 at 13:38
  • To check the values of the contents of your objects are the same you could adapt this [code](https://www.edutechional.com/2018/09/28/how-to-check-if-two-javascript-objects-have-the-same-values/) (there is also a [video](https://www.youtube.com/watch?v=GgfIby_T8yg) version) as per your needs and check your queries. Let me know if you find this information to be useful. – Daniel Ocando Jan 18 '21 at 13:41
  • Utils.js:61 Uncaught TypeError: Converting circular structure to JSON --> starting at object with constructor 'FirebaseAppImpl' | property 'firebase_' -> object with constructor 'Object' | property 'apps' -> object with constructor 'Array' --- index 0 closes the circle at JSON.stringify () – Mr.Drew Jan 18 '21 at 15:08

2 Answers2

1

If you're using v9 of the Web client SDK, the comparison is now done with the queryEqual function:

import {queryEqual} from "firebase/firestore";

console.log(queryEqual(query1, query2)); 
0

Use isEqual() as stated in the documentation here.

query1.isEqual(query2); //false

Mr.Drew
  • 939
  • 2
  • 9
  • 30