ID dynamic document firestore

时间:2018-09-22 22:46:28

标签: angular firebase google-cloud-firestore angularfire2

How can I make the ID of this document in firestore QEoevSjHlswgk44nVTsr dynamic, that is, change according to the IDs in that collection? I'm using angularfire2: ^5.0.0-rc.11

This is what I have:

firebase.service.ts

proyectos: Observable<Proyecto[]>;

getImagenDestacada() {
    this.proyectos = this.afs.collection('proyectos').doc('QEoevSjHlswgk44nVTsr').collection('archivos', ref => ref
    .orderBy('nombre','asc').limit(1)
    ).snapshotChanges().pipe(map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Proyecto;
        const id = a.payload.doc.id; 
        return { id, ...data };
      });
    }));
    return this.proyectos
    }

========================

I have tried the following:

firebase.service.ts

getImagenDestacada(id:string) {
this.proyectos = this.afs.collection('proyectos').doc(id).collection('archivos', ref => ref
.orderBy('nombre','asc').limit(1)
).snapshotChanges().pipe(map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data() as Proyecto;
    const id = a.payload.doc.id; 
    return { id, ...data };
  });
}));
return this.proyectos
}

portafolio.component.ts

archivos: Observable<Proyecto[]>;

this.archivos = this.fs.getImagenDestacada(this.id);

But I get the following error:

Error: Function CollectionReference.doc() requires its first argument to be of type string, but it was: undefined

2 个答案:

答案 0 :(得分:0)

尝试以下操作:const id = a.payload.doc.id.toString();

答案 1 :(得分:0)

错误是因为您致电

this.proyectos = this.afs.collection('proyectos').doc(id).collection ...

id未定义,因为在呼叫者中未定义this.id

根据the Firebase documentation,如果您想要动态生成的ID,则只需将参数保留为空白即可。将该行更改为:

this.proyectos = this.afs.collection('proyectos').doc().collection ...

然后Firebase会为您生成一个ID。

如果另一方面,您想要记录具有一个特定的ID,那么您需要一些代码来为您获取该ID,并将其传递给您的getImagenDestacada函数而不是{ {1}}。