How to query data across collections in Firestore?

自闭症网瘾萝莉.ら 提交于 2020-06-10 04:12:25

问题


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-model

If anyone knows an example of querying data across root-level collections in Firestore then please share the same.


回答1:


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



来源:https://stackoverflow.com/questions/47172132/how-to-query-data-across-collections-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!