Access a Firebase Document's ID Even when It's Not Stored in the Document with angularfire

Jorge Vergara
InstructorJorge Vergara

Share this video with your friends

Send Tweet
Published 6 months ago
Updated 6 months ago

There are 2 different ways to get a document's ID when using @angular/fire.

You can add the parameter { idField: 'id' } to your collection when using the collectionData() observable.

You can also use the observable collectionChanges() and access the internal metadata of the document to manually get the ID and add it to the resulting object.

Code sample: https://github.com/javebratt/angularfire-idField

Jorge Vergara: [0:01] Let's say you need to use your documents' IDs on your application, but you're not storing those IDs in the database. AngularFire lets you find the IDs and add them to the objects in two different ways.

[0:16] For the first one, let's say we're just pulling a regular collection of items from the database with collectionData. The quickest way to find our document's ID is using collectionData's properties. Here we can pass an extra property called idField, and we can say this idField is going to be id. What this is going to do is it's going to add the document's ID to the object, and it's going to use the key id for it.

[0:51] When we save, you see that now we have the IDs in the list right here. This is the fastest way, and you let AngularFire do all of the work for you. This should work for most people.

[1:05] The other way is if you need a little bit more control over the resulting object. For example, you want to add a prefix or something else to the ID. For that, instead of collectionData, we are going to use collectionChanges. CollectionChanges is going to take our query as a parameter. CollectionChanges is going to return all of the document's metadata.

[1:35] To get it to work the way we want to, we're going to pipe into this, because this is an observable, and we are going to get an import { map } from 'rxjs/operators'. In here, we have access to the actual document data, and we have access to the id from item.doc.id. Here, we will just need to return the id and the data. When I refresh, you see that I have the IDs here.

[2:24] When do you want to use these? Like I was saying before, when we might want to modify something about the ID or about any other property. Here, for example, I want to add...Maybe in our application we have some sort of prefix for the IDs, like something- and then the real ID. Then, what I added here, you'll see that we can see it inside of the application.