I have a project on Firebase Firestore and I want to execute a compound query between two documents under the same subcollection. I have already created the indexes that Firestore requires and the query executes perfectly if the fields are on the same document.
To exemplify my situation:
Take this structure:
- Users (root collection)
- User (document)
- userId
- username
- ...
--- Personalization (subcollection)
--- Alerts (document)
- myTags (array of strings)
- ...
--- Location (document)
- region (string)
- ...
I want to perform a query that first verifies if the user region
(/Users/{userId}/Personalization/Location
) is equal to a reference value. If so, I want it to verify if the array myTags
(/Users/{userId}/Personalization/Alerts
) contains a certain tag.
This is the closest I could get so far:
db.collectionGroup('Personalization').where('region', '==', 'California').where('myTags', 'array-contains', 'Macbook')
.get().then(querySnapshot => {
if (querySnapshot.empty) {
console.log('Result is empty');
} else {
console.log('Result found. ', querySnapshot.size, ' result(s).');
}
querySnapshot.forEach(doc => {
console.log(doc.id, ' => ', doc.data());
});
}).catch(error => {
console.error(error);
});
This query works perfectly if I have all my fields under the same document, like:
--- Personalization (subcollection)
--- Alerts (document)
- myTags (array of strings)
- region (string)
- ...
Also, I can make both queries work perfectly separately like this:
db.collectionGroup('Personalization').where('myTags', 'array-contains', 'Macbook').get().then(querySnapshot => {
querySnapshot.forEach(element => {
console.log('Search only by tag => ', element.id, ' => ', element.data());
});
Is there a way I can make the query work while still using two different documents under the same subcollection or I have obligatorily use the same document to make a compound query? Maybe there's some configuration on the index or something like that as well that I don't know about since I only followed the error link Firebase gives you when you first try a compound query to create the index.
Additional information:
- This code is being developed for deploy on Firebase Functions and it triggers every time there's an onWrite event on a certain collection I have.
Also, if someone knows some good examples of compound queries on Firestore I would appreciate it. I read the documentation already and saw a couple of videos from the Firebase team explaining how Firestore works, but I feel the lack of more complex samples to grasp how it works in practice.