Skip to content

Commit

Permalink
feat(afs): map document ID to the provided idField in a collection gr…
Browse files Browse the repository at this point in the history
…oup query (#2580)

Co-authored-by: James Daniels <jamesdaniels@google.com>
  • Loading branch information
simonxabris and jamesdaniels authored Nov 11, 2020
1 parent 0b3db49 commit dbf31d9
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
2 changes: 1 addition & 1 deletion docs/firestore/querying-collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ ngOnInit() {
...
// Get all the user's comments, no matter how deeply nested
this.comments$ = afs.collectionGroup('Comments', ref => ref.where('user', '==', userId))
.valueChanges({ idField });
.valueChanges({ idField: 'docId' });
}
```

Expand Down
13 changes: 13 additions & 0 deletions src/firestore/collection-group/collection-group.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,19 @@ describe('AngularFirestoreCollectionGroup', () => {
});
});

it('should return the document\'s id along with the data if the idField option is provided.', async () => {
const ITEMS = 4;
const DOC_ID = 'docId';
const { stocks } = await collectionHarness(afs, ITEMS);

const sub = stocks.valueChanges({idField: DOC_ID}).subscribe(data => {
const allDocumentsHaveId = data.every(d => d.docId !== undefined);

expect(allDocumentsHaveId).toBe(true);
sub.unsubscribe();
});
});

});

describe('snapshotChanges()', () => {
Expand Down
20 changes: 18 additions & 2 deletions src/firestore/collection-group/collection-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,28 @@ export class AngularFirestoreCollectionGroup<T= DocumentData> {

/**
* Listen to all documents in the collection and its possible query as an Observable.
*
* If the `idField` option is provided, document IDs are included and mapped to the
* provided `idField` property name.
*/
valueChanges(): Observable<T[]> {
valueChanges(): Observable<T[]>;
// tslint:disable-next-line:unified-signatures
valueChanges({}): Observable<T[]>;
valueChanges<K extends string>(options: {idField: K}): Observable<(T & { [T in K]: string })[]>;
valueChanges<K extends string>(options: {idField?: K} = {}): Observable<T[]> {
const fromCollectionRefScheduled$ = fromCollectionRef<T>(this.query, this.afs.schedulers.outsideAngular);
return fromCollectionRefScheduled$
.pipe(
map(actions => actions.payload.docs.map(a => a.data())),
map(actions => actions.payload.docs.map(a => {
if (options.idField) {
return {
[options.idField]: a.id,
...a.data()
} as T & { [T in K]: string };
} else {
return a.data();
}
})),
this.afs.keepUnstableUntilFirst
);
}
Expand Down

0 comments on commit dbf31d9

Please sign in to comment.