使用 where 子句 firestore 搜索时获取文档 id

3 javascript node.js firebase google-cloud-firestore

我希望能够获取我刚刚使用 firestore 中的 where 子句查询的文档的文档 ID。这是我目前的一个例子:

db.collection("Users").where('fullname', '==', 'foo bar').limit(5).get()
     .then(function (doc)
    {
        querySnapshot.forEach(function (doc)
        {
          //find document id
        }
    }
Run Code Online (Sandbox Code Playgroud)

由此,我希望能够获取我刚刚查询的文档 ID。我有什么办法可以做到这一点吗?

提前致谢。

小智 7

您可以在 Firestore 文档中找到您正在寻找的示例解决方案:

db.collection("cities").where("capital", "==", true)
.get()
.then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
})
.catch(function(error) {
    console.log("Error getting documents: ", error);
});
Run Code Online (Sandbox Code Playgroud)

您只需致电doc.id检索文档的 ID。

来源: https: //cloud.google.com/firestore/docs/query-data/get-data