从Cloud Firestore文档快照中获取文档引用

34

问题

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

我想要返回一个引用,以便稍后可以使用它来.update文档,而无需指定集合和使用documentSnapshot.id

path属性的文档在这里

我的代码

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个回答

45
在您的代码中,documentSnapshot 是一个类型为DocumentSnapshot的对象。看起来您假定它是一个类型为 DocumentReference 的对象。引用的目的是为了定位文档,快照的目的是在查询后接收文档内容,它们绝对不是相同的东西。DocumentSnapshot没有path属性。
如果您想获取从DocumentSnapshot中提取的文档的DocumentReference,则可以使用快照中的ref。然后您就可以获得ref的路径属性。
documentSnapshot.ref.path

2
嘿,Doug。谢谢你的帮助。我查看了DocumentSnapshot和DocumentReference文档,显然是我糊涂了一会儿。现在一切都正常了。我以前使用过documentSnapshot.ref.path,但找不到我在哪里使用它了。 - Jason Berryman
1
在Python中,应该使用reference而不是ref - Rivers Cuomo
我在文档中找不到这个。所以我不需要使用data()方法,我可以直接使用.ref? - satchel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接