【问题标题】:Cannot get data needed due to Mongoose Queries/Promises由于 Mongoose 查询/承诺,无法获取所需的数据
【发布时间】:2019-08-15 13:06:32
【问题描述】:

我正在尝试创建类似 Jeopardy 的游戏。我在数据库中有游戏的主题。打开页面时,我希望它从数据库中随机获取 6 个主题。我将它们放在一个数组中,然后将其传递给我的 ejs 文件。问题是,当我将数组传递给 ejs 文件时,它始终为空。我知道这是因为 Mongoose 的承诺(实际上是查询)。我的问题是我无法弄清楚如何处理这个问题。我已经阅读了 Mongoose 文档并到处搜索,但我无法弄清楚。

我尝试过使用回调,但它们通常只会让程序挂起,什么也不做。我尝试过使用 .then,但我一定是用错了,因为它没有达到我想要的效果。

app.get("/", function(request, response){
    //My array to put the topics into
    var questionArr = [];
    //I need to know the number of items in db for random
    var getQuestions = Questions.countDocuments({}, function(err, count){
        for(var i = 0; i < 6; i++){
            !function(i){
                var rand = math.randomInt(count);
                //Here I get a random topic and add to array
                //Seems to work and actually get it
                Questions.findOne().skip(rand).exec(function(err, result){
                    questionArr.push(result);
                });
            }(i);
        }
    });

    //I thought this would make it wait for the function to finish so
    //that I could have my full array, but apparently not
    getQuestions.then(() => {
        //this runs before the other functions and give me a length of 0
        console.log(questionArr.length);
        response.render("jeopardy.ejs", {questions: questionArr});
    });
});

我只需要在从数据库中获取信息后运行渲染。但是,它仍然只运行一个空数组。感谢您的帮助,我对异步很陌生。

【问题讨论】:

标签: javascript node.js mongoose


【解决方案1】:

我发现您的代码存在一些问题:

1) 你混合了承诺和回调,这让事情变得更加复杂。该代码不起作用主要是因为您没有等待 Questions.findOne() 结果。

2) 没有 Math.randomInt

为了使其正常工作,它必须类似于以下内容:

Questions.countDocuments()
    .then((count) => {
        return Promise.all([...new Array(6)].map(() => {
            const rand = Math.floor(Math.random() * Math.floor(count));
            return Questions.findOne().skip(rand).exec();
        }))
    })
    .then((questionArr) => {
        response.render("jeopardy.ejs", {questions: questionArr});
    });

最好是使用 async/await,这将使其更具可读性

app.get("/", async function(request, response){
    const count = await Questions.countDocuments();
    const questionArr = await Promise.all([...new Array(6)].map(() => {
        const rand = Math.floor(Math.random() * Math.floor(count));
        return Questions.findOne().skip(rand).exec();
    }));
    response.render("jeopardy.ejs", {questions: questionArr});
});

另外请记住,您最好进行适当的错误处理,但这是另一篇文章的主题:)

【讨论】:

  • 效果很好,非常感谢。我需要一些时间来查看并理解它,但感谢您的建议和帮助。现在我有了一些有用的东西,我可以努力理解这一切。我肯定会进行错误处理,只是想先做点什么。非常感谢!
  • 嘿,我通读了代码,现在我明白了。非常感谢,我现在掌握了一些异步的东西。不过我有一个问题,三个点的数组格式是什么?我以前从未遇到过。这里是:[...new Array(6)]
  • 嘿@LeeMorgan,这是数组破坏。在这种情况下,这种模式有助于做某件事 X 次。
猜你喜欢
  • 2019-10-21
  • 2020-12-23
  • 2021-10-23
  • 1970-01-01
  • 2018-08-17
  • 2020-09-28
  • 1970-01-01
  • 2021-09-04
  • 2021-05-23
相关资源
最近更新 更多