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

有些话、适合烂在心里 提交于 2019-12-08 07:55:34

问题


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?


回答1:


You can do it solely using Javascript native array API .find(), and it will save you a couple lines of code:

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

Or you can use the .first() operator and supply its first-met condition:

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

Note that there is a fundamental difference in how the filtering works behind the scene. I personally prefer the Javascript's native function, as I feel it's kinda redundant to transform the observable using from(array) just so that it is emitting the array sequence one by one.

Also note that by doing ref => ref.where('bookingId', '==', id), you filtering actually happens at query level (aka not at client side). If you are confident that the number of payments retrieved won't be big, then it's fine to let the client side do the filtering; else its always better to offload the processing part to the server.




回答2:


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.



来源:https://stackoverflow.com/questions/51834511/get-a-single-document-by-foreign-key-in-using-rxjs-and-angularfirestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!