Search code examples
angularfirebasegoogle-cloud-firestoreangularfire

Angular Firebase: take(1) returns multiple documents


I'm trying to get a single document from the Products collection in Firestore. ProductService handles the query and returns a subscription:

//ProductService
export class ProductService {
...  
getByPermalink(permalink: string) {
    return this.db.collection('products', ref => ref.where('permalink','==', permalink ))
      .valueChanges({ idField: 'id' })
      .pipe(take(1)) 
  }
}

Then calls it on my component:

//ProductComponent
this.productService.getByPermalink(this.permalink).subscribe((res: any) => {
   this.product = res
   console.log('product', this.product)
})

All of this works only it doesn't seem to honor the take(1) call and returns multiple documents when there are multiple matches to the query.

Any help would be greatly appreciated.


Solution

  • The take(1) makes it so you only get data one time (as opposed to getting updates over time as the database changes). But that data will contain whatever is returned by your query. If you only want one document, you'll need to restrict the query, not the observable. You can do this with the limit function:

    return this.db
      .collection("products", (ref) =>
        ref.where("permalink", "!=", permalink).limit(1)
      )
      .valueChanges({ idField: "id" })
      .pipe(take(1));