Skip to content

Commit dbf31d9

Browse files
feat(afs): map document ID to the provided idField in a collection group query (#2580)
Co-authored-by: James Daniels <[email protected]>
1 parent 0b3db49 commit dbf31d9

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

docs/firestore/querying-collections.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ ngOnInit() {
193193
...
194194
// Get all the user's comments, no matter how deeply nested
195195
this.comments$ = afs.collectionGroup('Comments', ref => ref.where('user', '==', userId))
196-
.valueChanges({ idField });
196+
.valueChanges({ idField: 'docId' });
197197
}
198198
```
199199

src/firestore/collection-group/collection-group.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,19 @@ describe('AngularFirestoreCollectionGroup', () => {
134134
});
135135
});
136136

137+
it('should return the document\'s id along with the data if the idField option is provided.', async () => {
138+
const ITEMS = 4;
139+
const DOC_ID = 'docId';
140+
const { stocks } = await collectionHarness(afs, ITEMS);
141+
142+
const sub = stocks.valueChanges({idField: DOC_ID}).subscribe(data => {
143+
const allDocumentsHaveId = data.every(d => d.docId !== undefined);
144+
145+
expect(allDocumentsHaveId).toBe(true);
146+
sub.unsubscribe();
147+
});
148+
});
149+
137150
});
138151

139152
describe('snapshotChanges()', () => {

src/firestore/collection-group/collection-group.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,12 +76,28 @@ export class AngularFirestoreCollectionGroup<T= DocumentData> {
7676

7777
/**
7878
* Listen to all documents in the collection and its possible query as an Observable.
79+
*
80+
* If the `idField` option is provided, document IDs are included and mapped to the
81+
* provided `idField` property name.
7982
*/
80-
valueChanges(): Observable<T[]> {
83+
valueChanges(): Observable<T[]>;
84+
// tslint:disable-next-line:unified-signatures
85+
valueChanges({}): Observable<T[]>;
86+
valueChanges<K extends string>(options: {idField: K}): Observable<(T & { [T in K]: string })[]>;
87+
valueChanges<K extends string>(options: {idField?: K} = {}): Observable<T[]> {
8188
const fromCollectionRefScheduled$ = fromCollectionRef<T>(this.query, this.afs.schedulers.outsideAngular);
8289
return fromCollectionRefScheduled$
8390
.pipe(
84-
map(actions => actions.payload.docs.map(a => a.data())),
91+
map(actions => actions.payload.docs.map(a => {
92+
if (options.idField) {
93+
return {
94+
[options.idField]: a.id,
95+
...a.data()
96+
} as T & { [T in K]: string };
97+
} else {
98+
return a.data();
99+
}
100+
})),
85101
this.afs.keepUnstableUntilFirst
86102
);
87103
}

0 commit comments

Comments
 (0)