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'},
]
.valueChanges()
returns only data without any meta data. you can use .snapshotChanges()
for that
this.Post_collection = this.afs.collection('posts');
return this.Posts = this.Post_collection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
});
also import import { Observable } from 'rxjs/Observable';
For your second question how to add id when pushing data to firestore. try
//get id from firestore
let id = this.afs.createId();
this.post = {
id:id,
name:'name',
description:'description'
}
this.afs.collection('posts').doc(id).set(this.post).then();
Now you can use .valueChanges()
to get the data.