ID 动态文档 Firestore [英] ID dynamic document firestore
问题描述
如何让firestore QEoevSjHlswgk44nVTsr
中这个文档的ID 动态化,即根据那个集合中的ID 改变?我正在使用 angularfire2:^5.0.0-rc.11
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
这就是我所拥有的:
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
}
========================
========================
我尝试了以下方法:
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);
但我收到以下错误:
错误:Function CollectionReference.doc() 要求它的第一个参数是字符串类型,但它是:undefined
Error: Function CollectionReference.doc() requires its first argument to be of type string, but it was: undefined
推荐答案
错误是因为当你调用
this.proyectos = this.afs.collection('proyectos').doc(id).collection ...
id
未定义,因为 this.id
在调用方中未定义.
id
is undefined, because this.id
was undefined in the caller.
根据 Firebase 文档,如果您愿意一个动态生成的 id 然后你可以简单地将参数留空,即.将该行更改为:
According to the Firebase documentation, if you want a dynamically generated id then you can simply leave the parameter blank, ie. change that line to be :
this.proyectos = this.afs.collection('proyectos').doc().collection ...
然后 Firebase 会为您生成一个 ID.
Then Firebase will generate an ID for you.
另一方面,如果您希望记录具有特定的 ID,那么您需要一些代码来为您获取该 ID 并将其传递给您的 getImagenDestacada
函数而不是 this.id
.
If, on the other hand, there is a specific ID you want the record to have, then you need to have some code to get that ID for you and pass that through to your getImagenDestacada
function instead of this.id
.
这篇关于ID 动态文档 Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!