Firestore查询具有多个值的循环 [英] Firestore query for loop with multiple values

查看:61
本文介绍了Firestore查询具有多个值的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用字符串中保存的数据来检索许多Firestore文档.这个想法是,对于数组中的每个值,我将使用Firestore查询来检索与该查询匹配的文档并将其推送到另一个数组.我在实现此目标时遇到了一些问题.到目前为止,我已经尝试过:

I am attempting to retrieve a number of Firestore documents using data held in a string. The idea is that for each value in the array, i'd use Firestore query to retrieve the document matching that query and push it to another array. I am having a few issues achieving this. So far i've tried:

exports.findMultipleItems = functions.https.onRequest((request, response) => {
    var list = ["item1", "item2", "item3", "item4"];

    var outputList = [];

    for (var i = 0; i < list.length; i++) {
        console.log("Current item: " + list[i]);
        let queryRef = db.collection("items").where('listedItems', 'array-contains', list[i]).get()
            .then(snapshot => {
                if (snapshot.empty) {
                    console.log('No matching documents.');
                }

                snapshot.forEach(doc => {
                    outputList.push(doc.data());
                });
                return;
            })
            .catch(err => {
                console.log('Error getting documents', err);
            });
    }

    response.send(JSON.stringify(outputList));

});

我不确定,但是我认为问题之一是for循环在查询有机会完成之前就已经完成.

I'm not entirely sure but i think one of the issues is that the for loop is being completed before the queries have a chance to finish.

P.s-正在使用Admin SDK通过Cloud Functions运行.

P.s - this is being ran through Cloud Functions using Admin SDK.

推荐答案

您的queryRef实际上不是引用.这是一个承诺,在您获得/然后/接获完成后可以解决.您需要使用这些承诺来确定它们何时全部完成.只有在数组全部完成后,才会填充该数组,只有这样,才可以安全地使用该数组发送响应.

Your queryRef is not actually a reference. It's a promise that resolves after your get/then/catch have finished. You need to use these promises to determine when they're all complete. The array will be populated only after they are all complete, and only then is it safe to send the response using that array.

将所有promise收集到一个数组中,并使用Promise.all()获得一个新的promise,这些promise在它们全部完成后会解决:

Collect all the promises into an array, and use Promise.all() to get a new promise that resolves after they're all complete:

exports.findMultipleItems = functions.https.onRequest((request, response) => {
    var list = ["item1", "item2", "item3", "item4"];

    var outputList = [];
    const promises = [];

    for (var i = 0; i < list.length; i++) {
        console.log("Current item: " + list[i]);
        let promise = db.collection("items").where('listedItems', 'array-contains', list[i]).get()
            .then(snapshot => {
                if (snapshot.empty) {
                    console.log('No matching documents.');
                }

                snapshot.forEach(doc => {
                    outputList.push(doc.data());
                });
                return;
            })
            .catch(err => {
                console.log('Error getting documents', err);
            });
        promises.push(promise);
    }

    Promise.all(promises).then(() => {
        response.send(JSON.stringify(outputList));
    }
    .catch(err => {
        response.status(500);
    })

});

您可能希望使用这些教程来更好地了解如何处理Cloud Functions中的承诺:

You might want to use these tutorials to better understand how to deal with promises in Cloud Functions:

https://firebase.google.com/docs/functions/video-系列/

这篇关于Firestore查询具有多个值的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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