Search code examples
rxjsangularfire2

Get a single document by foreign key in using RxJs and AngularFirestore


I've written a query that looks like this:

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

Where a Payment object has a unique reference to a Booking id. I want to find the Payment for a given ID.

This seems like quite a convoluted way to right this query.

Is there a simpler way to do this - including if there is a code smell here that makes this hard?


Solution

  • A little bit simpler is:

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

    this will returned undefined if the payment is not found.