I have this function that gets all the posts and I want to get the id of the post any idea how to get the id of the post or How to include the id when I add the document to the collection
get_the_posts(){
this.Post_collection = this.afs.collection('posts');
return this.Posts = this.Post_collection.valueChanges();
}
[
{ name: 'post 1 name' description: 'post description'},
{ name: 'post 2 name' description: 'post description'},
{ name: 'post 3 name' description: 'post description'},
]
[
{ id: 'm9mggfJtClLCvqeQ', name: 'post 1 name' description: 'post description'},
{ id: 'm9mggfJtCldsadaf', name: 'post 2 name' description: 'post description'},
{ id: 'm9mggfJtCdsasavq', name: 'post 3 name' description: 'post description'},
]
As of May, 10, 2019 you can now use:
valueChanges({idField?: string})
and pass in an optional field name that will contain the id of the document.
Such as in your original post:
get_the_posts(){
this.Post_collection = this.afs.collection('posts');
return this.Posts = this.Post_collection.valueChanges({ idField: 'id' });
}
This would indeed return your objects in your desired output.
From the Collections documentation:
Streaming collection data
There are multiple ways of streaming collection data from Firestore.
valueChanges({idField?: string})
What is it? - The current state of your collection. Returns an Observable of data as a synchronized array of JSON objects. All Snapshot metadata is stripped and just the document data is included. Optionally, you can pass an options object with an idField key containing a string. If provided, the returned JSON objects will include their document ID mapped to a property with the name provided by idField.
[Emphasis mine]