How to query data across collections in Firestore?

后端 未结 1 1147
陌清茗
陌清茗 2021-01-02 14:42

It is written in the documentation below that \"If you need to query data across collections, use root-level collections.\" https://cloud.google.com/firestore/docs/data-mode

相关标签:
1条回答
  • 2021-01-02 15:08

    I'm not sure of your specific scenario. Here's how to get comments (from 'commentsCollection' collection) related to an article.

    Assume article documents are set up like this:

    firestore: articlesCollection/1234

    {
        title: "How to FireStore",
    }
    

    And comments documents are set up like this:

    firestore: commentsCollection/ABCD

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

    firestore: commentsCollection/EFGH

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

    Given an article document id...

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

    If the given article id were 1234, the comment ABCD would be the result. If the given article id were 5678, the comment EFGH would be the result.

    Including the article doc query it would look something like this:

    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());
                    });
                });
        });
    

    Modified from firestore docs: https://cloud.google.com/firestore/docs/solutions/arrays

    0 讨论(0)
提交回复
热议问题