首页 > 解决方案 > firebase subquery and also head query in next js as getinitialprops

问题描述

I want to have the query with subquery. Lets see the first query:

static async getInitialProps(ctx) {
    let product = []
    const PostId = ctx.query.pid;
    await firebase.firestore()
    .collection('products')
    .doc(PostId)
    .get()
    .then(querySnapshot => {
        querySnapshot.forEach(doc => {
            console.log(doc.id, " => ", doc.data());
        });
        return product
    })
    .catch(error => {
      console.log('error', error)
    })
    

return {product: product[0]}
}

now I got the information from that query, but I also need subcollections. I found out how to get all subcollection like this, but then I lose the data from above query.

static async getInitialProps(ctx) {
    let product = []
    const PostId = ctx.query.pid;
    await firebase.firestore()
    .collection('products')
    .doc(PostId)
    .collection('offers')
    .orderBy('position', 'asc')
    .get()
    .then(querySnapshot => {
        querySnapshot.forEach(doc => {
            console.log(doc.id, " => ", doc.data());
        });
        return product
    })
    .catch(error => {
      console.log('error', error)
    })
    

return {product: product[0]}
}

So is it possible to combine this toghether and get all from collection('products').doc(postID) and all from collection('products').doc(postID).collection('offers') ? So all in one query.

标签: reactjsfirebasegoogle-cloud-firestorenext.js

解决方案


不,一次查询是不可能的。Firestore 查询是浅层的,只考虑正在查询的集合中的文档。集合之间没有类似 SQL 的连接。如果您需要来自多个集合的文档,则必须执行多个查询。

可以从多个集合中获取文档的唯一查询类型是集合组查询,并且只考虑具有相同名称的所有集合中的文档。您可以使用它来查询所有“优惠”子集合中的所有文档,但您将无法按父文档中的任何内容进行过滤。


推荐阅读