从documentSnapshot获取Cloud Firestore文档引用

时间:2018-02-22 18:12:40

标签: javascript firebase google-cloud-firestore firebase-admin

问题

我正在尝试从查询中检索文档引用。我的代码返回undefined。我可以通过提取documentSnapshot.ref的各个部分来获取路径,但这并不简单。

我想要返回的是一个参考资料,然后我可以将其用于.update文档,而无需指定集合并使用documentSnapshot.id

path媒体资源的文档为here

我的代码

const db = admin.firestore();

return db.collection('myCollection').get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`documentReference.id   = ${documentSnapshot.id}`);
    console.log(`documentReference.path = ${documentSnapshot.path}`);
    // console.log(`documentReference.ref = ${JSON.stringify(documentSnapshot.ref)}`);
  });
});

输出

documentReference.id   = Jez7R1GAHiR9nbjS3CQ6
documentReference.path = undefined
documentReference.id   = skMmxxUIFXPyVa7Ic7Yp
documentReference.path = undefined

1 个答案:

答案 0 :(得分:11)

在您的代码中,documentSnapshotDocumentSnapshot类型的对象。看起来你假设它是DocumentReference类型的对象。参考的目的是找到文档。快照的目的是在查询文档后接收文档的内容 - 它们肯定不是同一个东西。 DocumentSnapshot没有path属性。

如果您需要DocumentSnapshot中提取的文档的DocumentReference,则可以使用快照中的ref。然后你可以获得ref的路径属性:

documentSnapshot.ref.path