How to include the document id in Firestore collection in Angular 5

后端 未结 6 1097
温柔的废话
温柔的废话 2021-01-02 11:28

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

6条回答
  •  无人及你
    2021-01-02 11:44

    .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.

提交回复
热议问题