gpt4 book ai didi

node.js - 渲染 View 之前的多个 Mongoose 查询

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:41 24 4
gpt4 key购买 nike

我有一个包含多个下拉列表的表单,需要使用 MongoDB 数据库中的值填充,在我的路由文件代码中看起来像这样:

Make.find({},function(err,allMakes){
if(err){
console.log("error while trying to get all makes from the database");
}else{
makes = allMakes;
}

Color.find({},function(err,allColors){
if(err){
console.log("error while trying to get all colors from the database");
}else{
colors = allColors;
}

我有 8 次需要查询数据库,然后将结果放入局部变量中,以便将其作为参数传递给渲染函数,如下所示:

res.render("viewname",{makes:makes,colors:colors....etc}); 

问题是在我的 View 文件中我的参数未定义。

异步nodejs代码有什么解决方案吗?!

最佳答案

MongoDB 调用是异步的,这意味着品牌、颜色等的值不会在 res.render("viewname"); 之前设置。正在被调用。您需要嵌套异步调用,使用 Promise.all,或者最好使用像 async 这样的库。并行运行数据库调用,然后仅在所有数据库回调设置了应传递给 View 的值后调用 res.render。

例如,如果您嵌套调用:

Make.find({}, function(err,allMakes) {
if (err) {
console.log("error while trying to get all makes from the database");
} else {
makes = allMakes;
}

Color.find({}, function(err,allColors) {
if (err) {
console.log("error while trying to get all colors from the database");
} else {
colors = allColors;
}

res.render("viewname",{makes:makes,colors:colors....etc});
}
}

关于node.js - 渲染 View 之前的多个 Mongoose 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38922079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com