-
Notifications
You must be signed in to change notification settings - Fork 2.2k
How to add an OrderBy or Where to a collectionData query #3047
-
Hi all,
Still not clear how to do an "orderBy" or a "where" filter in the collection query strings. I'm setting up a service in my app like so:
dbCountries: Observable<any[]>;
public getDBcountries() {
if (!this.dbCountries) {
const readCollection = collection(this.firestore, countryCollectName.collectName);
this.dbCountries = collectionData(readCollection, { idField: 'id' }).pipe(
shareReplay(1)
) as Observable<any[]>;
}
return this.dbCountries;
}
Anyone having any luck?
Beta Was this translation helpful? Give feedback.
All reactions
I had the same issue and finally found the fix myself!
You will have to create one or more constraints, which is a where() for example.
Then you use a query, in which you pass the collection you want to query and the queryConstraints
Example in my code where I used 2 constraints to get orders from a specific date:
const ordersRef = collection(this.firestore, this.ORDER_COLLECTION_NAME);
const startDateConstraint = where('date', '>=', date1);
const endDateConstraint = where('date', '<', date2);
const ordersByTodayQuery = query(ordersRef, startDateConstraint, endDateConstraint);
return collectionData(ordersByTodayQuery) as Observable<IOrder[]>;
I hope this will help som...
Replies: 2 comments 1 reply
-
I had the same issue and finally found the fix myself!
You will have to create one or more constraints, which is a where() for example.
Then you use a query, in which you pass the collection you want to query and the queryConstraints
Example in my code where I used 2 constraints to get orders from a specific date:
const ordersRef = collection(this.firestore, this.ORDER_COLLECTION_NAME);
const startDateConstraint = where('date', '>=', date1);
const endDateConstraint = where('date', '<', date2);
const ordersByTodayQuery = query(ordersRef, startDateConstraint, endDateConstraint);
return collectionData(ordersByTodayQuery) as Observable<IOrder[]>;
I hope this will help someone!
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 2 -
🎉 2
-
Thanks, here is a version I got working for making my country list to sort:
// Make a country list service available across all pages
dbCountries: Observable<any[]>;
public getDBcountries() {
if (!this.dbCountries) {
const readCollection = collection(this.firestore, countryCollectName.collectName);
const readQuery = query(readCollection, orderBy('countrySimple', 'asc')); // asc or desc
this.dbCountries = collectionData(readQuery).pipe(
shareReplay(1)
) as Observable<any[]>;
} // can get the document ids using: readQuery, { idField: 'id' }
return this.dbCountries;
}
Beta Was this translation helpful? Give feedback.
All reactions
-
Thanks for this discussion. This example really should be part of the documentation.
Beta Was this translation helpful? Give feedback.