Angular Firestore Valuechanges get document reference

Viewed 738

I'm using Angular with google cloud firestore to load data. I also have a model class, let's call it IMyModel

export interface IMyModel{
    data: any;
    id: string;
}

of which the id is the id of the document on firestore. I can easily load this through

var docs = this.firestore.collection('myCollection').valueChanges({ idField: 'id' }) as Observable<IMyModel[]>; This neatly works.

But now, I also want this functionality with the document reference. Lets's say I alter the model

export interface IMyModel{
    data: any;
    documentReference: DocumentReference;
}

How can I now insert the documentReference field? I already tried

var docs = this.firestore.collection('myCollection').valueChanges({ ref: 'documentReference', }) as Observable<IMyModel[]>;

But this does not insert the field.

2 Answers

valueChanges() gives you an observable. You can do .pipe(map(items => items.map(item => yourFunction(item)))) to transform the data to your liking:

interface IMyModel {
  data: any;
  ref: DocumentReference;
}
const myCollection = this.firestore.collection<{ data: any }>('myCollection');
const itemsWithId$ = myCollection.valueChanges({ idField: 'id' });
const itemsWithRef$: Observable<IMyModel[]> = itemsWithId$.pipe(
  map(itemsWithId => {
    return itemsWithId.map(item => {
      return {
        data: item.data,
        ref: myCollection.doc(item.id).ref,
      };
    });
  }),
);

Can you please try with this solution?

export interface Item { id: string; name: string; }
@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let item of items | async">
        {{ item.name }}
      </li>
    </ul>
  `
})
export class AppComponent {
  private itemsCollection: AngularFirestoreCollection<Item>;
  items: Observable<Item[]>;
  constructor(private readonly afs: AngularFirestore) {
    this.itemsCollection = afs.collection<Item>('items');
    // .valueChanges() is simple. It just returns the 
    // JSON data without metadata. If you need the 
    // doc.id() in the value you must persist it your self
    // or use .snapshotChanges() instead. See the addItem()
    // method below for how to persist the id with
    // valueChanges()
    this.items = this.itemsCollection.valueChanges();
  }
}

For more reference please refer this link.

Related