AngularFire Firestore get single document after collection querying by custom key

Haginus Source

I'm new in the Angular and Firebase world, and so I got into one problem that I can't solve.

I want to look for a document by a custom key, other than the id. So I set up a service:

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap'
import { Product, ProductId } from './models';

export class ProductsService {
  productsCollection: AngularFirestoreCollection<Product>;
  products: Observable<ProductId[]>;
  product: Observable<Product>;

  constructor(public afs: AngularFirestore) { 
    this.productsCollection = this.afs.collection<Product>('products');

  getProduct(query) : Observable<Product> {
    if( {
      this.product = this.productsCollection.doc<Product>(;
      return this.product;
    } else if(query.url) {
      this.product = this.afs.collection<Product>('products', ref => ref.where('url', '==', query.url)
      .limit(1)).valueChanges().flatMap(result => result);
      return this.product;



function should be able to get a doc in two ways - by id and by custom unique field in the doc

query: { 'url': 'CUSTOM KEY'}

But the second one doesn't work. I want to retun it a single document Observable like I did in when I was looking by id. How can I do that? In the current code I get a compiler error.



comments powered by Disqus