如何在Firestore中跨集合查询数据? [英] How to query data across collections in Firestore?

查看:128
本文介绍了如何在Firestore中跨集合查询数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

我不确定您的特定方案.这是获取与文章相关的评论(从"commentsCollection"集合中获取评论的方法).

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

firestore: articlesCollection/1234

{
    title: "How to FireStore",
}

注释文档设置如下:

firestore: commentsCollection/ABCD

firestore: commentsCollection/ABCD

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

firestore: commentsCollection/EFGH

firestore: commentsCollection/EFGH

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

给出文章文档ID ...

Given an article document id...

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

如果给定的商品ID为1234,则结果为ABCD.如果给定的商品ID为5678,则结果为评论EFGH.

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.

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

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


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


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

这篇关于如何在Firestore中跨集合查询数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆