Search code examples
google-cloud-firestoreangularfire2

Simplest way to get a single document with angularfire2


I'm trying to have a basic form so that I can update data. I can query a full collection (and optionally could maybe filter on client-side the data I need, event if it didn't yet work for me).

I can query a single doc when I know the id. But I'd like to query a collection with business criteria and be able to add it in my view (and of course get a way to update data when updated by the form.)

Actually my question seems to be really close to Get a single document by foreign key in using RxJs and AngularFirestore But :

  • getting all data and filter it after seems to me a bad solution

  • I tried, but I'm not sure to understand the meaning (the type) of allPayments and payment (for this I guess it's a business class if so, okay) in this given example :

    getPaymentByBookingId(id: string): Observable<Payment> {
     return this.afs.collection<Payment>('payments')
         .valueChanges()
         .pipe(
        map(allPayments=>allPayments.find(payment=>payment.bookingId === id))
       );
     }
    

I just got an

    Cannot read property '<my_attribute' of undefined

which suppose the get is returning a null.


Solution

  • As you suggested, filtering on the client side is not the ideal way to do this. You need to query the collection on bookingId and then limit() this to one result.

    This will still return an array with one item (limit(1)), but you can flatten the result with flatMap() to get a single Payment:

    getPaymentByBookingId(id: string): Observable<Payment> {
        return this.afs
            .collection<Payment>('payments', ref => ref.where('bookingId', '==', id).limit(1))
            .valueChanges()
            .pipe(
                flatMap(payments => payments)
            );
    }