Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 495
Eric Avatar asked Oct 18 '22 03:10

Eric


1 Answers

Use flatmap to return the single document data:

First import the .flatMap() property.

import { AngularFirestore } from 'angularfire2/firestore';
import 'rxjs/add/operator/mergeMap';

Then query your collection and limit it to 1 document:

this.afs.collection('collection', ref => ref.where('value', '==', true) 
.limit(1)).valueChanges().flatMap(result => result);

Then you can subscribe to that and it will return the flatened json instead of an array.

EDIT:

And you can just do like this to use it in your html directly:

this.userInfo = this.afs.collection('collection', ref => ref.where('value', 
'==', true).limit(1)).valueChanges().flatMap(result => result);

In the html code:

<p>{{ (userInfo | async)?.duration }}</p>
like image 80
Tiffan Meloney Avatar answered Oct 20 '22 21:10

Tiffan Meloney