如何在Firestore中跨集合查询数据?

时间:2017-11-08 05:25:30

标签: google-cloud-firestore

它写在下面的文档中"如果需要跨集合查询数据,请使用根级集合。" https://cloud.google.com/firestore/docs/data-model

如果有人知道在Firestore中跨根级别集合查询数据的示例,请分享相同内容。

1 个答案:

答案 0 :(得分:1)

我不确定你的具体情况。以下是如何获取与文章相关的评论(来自'commentsCollection'集合)。

假设文章文件的设置如下:

firestore: articlesCollection / 1234

{
    title: "How to FireStore",
}

评论文件的设置如下:

firestore: commentsCollection / ABCD

{
    comment: "Great article!",
    articleRef: {
        "1234": true
    }
}

firestore: commentsCollection / EFGH

{
    comment: "Another comment on a different article",
    articleRef: {
        "5678": true
    }
}

鉴于文章文件ID ...

let articleComments = db.collection("commentCollection")
    .where('articleRef.' + articleId, '==', true)
    .get()
    .then(() => {
        // ...
    });

如果给定的文章ID是1234,那么评论ABCD就是结果。如果给定的文章ID是5678,那么注释EFGH就是结果。

包括文章doc查询,它看起来像这样:

db.collection("articlesCollection")
    .doc(articleId)
    .get()
    .then(article => {
        firebase.firestore().collection("commentsCollection")
            .where('articleRef.' + article.id, '==', true)
            .get()
            .then(results => {
                results.forEach(function (comment) {
                    console.log(comment.id, " => ", comment.data());
                });
            });
    });

从firestore文档修改: https://cloud.google.com/firestore/docs/solutions/arrays