Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Firestore上获取文档中的集合?_Javascript_Firebase_Google Cloud Firestore - Fatal编程技术网

Javascript 如何在Firestore上获取文档中的集合?

Javascript 如何在Firestore上获取文档中的集合?,javascript,firebase,google-cloud-firestore,Javascript,Firebase,Google Cloud Firestore,我有一个名为users的集合,在每个文档的用户中都有一个名为monthlies的集合,我想要得到它。 结构如下: 现在,我尝试使用以下方法获取它: var getUsers = async function() { var db = firebase.firestore() var users = await firebase .firestore() .collection("users")

我有一个名为
users
的集合,在每个文档的用户中都有一个名为
monthlies
的集合,我想要得到它。 结构如下:

现在,我尝试使用以下方法获取它:

var getUsers = async function() {
        var db = firebase.firestore()
        var users = await firebase
            .firestore()
            .collection("users")
            .get();
        return users
}

var getMonthlyByUserId = async function () {
    var users = await getUsers()
    users.forEach(element => {
        var monthlies = element.collection('monthlies').get()
        console.log(monthlies.docs.map(doc => doc.data()))
    })
}

但它什么也没印出来。目标是迭代集合中所有文档的月份。

在代码中,
元素是一个类型对象。它没有名为
collection()
的方法,因此我希望您的代码会因日志中的错误而崩溃

如果要引用在QueryDocumentSnapshot表示的文档下组织的子集合,应基于其属性:

users.forEach(snapshot => {
    var monthlies = snapshot.ref.collection('monthlies').get()
    console.log(monthlies.docs.map(doc => doc.data()))
})

或者,如果您只想查询名为“monthly”的所有子集合中的所有文档,您可以使用一个简单的方法来简化它。

除了Doug指出的问题之外(您需要使用
QueryDocumentSnapshot
ref
属性),还需要考虑该方法是异步的

这样做

users.forEach(snapshot => {
    var monthlies = snapshot.ref.collection('monthlies').get()
    console.log(monthlies.docs.map(doc => doc.data()))
})
这是行不通的

如果无法使用集合组查询(例如,假设您的
getUsers()
函数只返回所有用户的子集,例如给定国家/地区的所有用户),则可以使用以下方法:

var getMonthlyByUserId = async function () {
    const users = await getUsers();
    const promises = [];
    users.forEach(snapshot => {
      promises.push(snapshot.ref.collection('monthlies').get());
    });
    const monthlies = await Promise.all(promises);
    monthlies.forEach(snapshotArray => {
      console.log(snapshotArray.docs.map(doc => doc.data()));
    });
 }
您可以使用本文中描述的技术,了解如何在
forEach()中使用async/wait

getUsers()
返回集合,首先循环该集合中的每个文档,然后循环每个文档中的每个
月。