Search code examples
javascriptangularrxjsgoogle-cloud-firestoreangularfire5

Firestore : Retrieve a single document


I want to retrieve a single document from Firestore. So I do not mean the list of documents in the collection (I know how to do that). Let's say I know one of the key-value pair of the document and I would like to find and retrieve the document into Angular 4.

interface Occupations {
	duration: number;
	id_entity: number;
	id_job: number;
	id_user: number;
	salary: number;
	start_time: number;
}

occupationDoc:AngularFirestoreDocument<Occupations>;
occupation: Observable<Occupations>;
<h1>A specific post:</h1>

  <h3>{{ (occupation | async)?.salary }}</h3>
  <p>{{ (occupation | async)?.id_user }}</p> 
  <p>{{ (occupation | async)?.duration }}</p> 
  <p>{{ (user | async)?.lastName }}</p> 


Solution

  • This is the solution I came up with :

    //HTML
    {{userInfo}}
    
    //TypeScript
    this.afs.collection('Occupations',
    ref => ref.where('id_user', '==', this.idAuth)  
    .limit(1))
    .valueChanges()
    .flatMap(result => result)
    .subscribe(
        v => {
            let y = JSON.parse(JSON.stringify(v));
            this.userInfo = y.duration;                 
        }, 
        (error) => {
                 console.log(error);
        }, () => {
            console.log('Finished');
        });