【发布时间】: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});
});
});
我只需要在从数据库中获取信息后运行渲染。但是,它仍然只运行一个空数组。感谢您的帮助,我对异步很陌生。
【问题讨论】:
-
在猫鼬中获取随机文档的一种更简单有效的方法:stackoverflow.com/questions/39277670/…
标签: javascript node.js mongoose