如何在Angular 5的Firestore集合中包含文档ID [英] How to include the document id in Firestore collection in Angular 5

查看:55
本文介绍了如何在Angular 5的Firestore集合中包含文档ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此功能,该功能可以获取所有帖子,并且我想获取该帖子的ID 将文档添加到集合中时如何获取帖子ID或如何包含ID的任何想法

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()仅返回没有任何元数据的数据.您可以为此使用.snapshotChanges()

.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 };
  });
});

还导入import { Observable } from 'rxjs/Observable';

您的第二个问题是在将数据推送到Firestore时如何添加ID.尝试

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();

现在您可以使用.valueChanges()来获取数据.

Now you can use .valueChanges() to get the data.

这篇关于如何在Angular 5的Firestore集合中包含文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆