我正在创建车队管理应用程序,我已经设置了车辆的品牌和模型,并且我在我的数据库模型中建立了一对多的关系。
我正在试图展示车辆制造及其型号,但是,它似乎不起作用,下面是我的路线文件中的代码:
router.get("/new",function(req,res){
var selectedMake;
Make.find({},function(err,result){
if(err){
console.log("an error occured while fetching the data");
}else{
if(req.query.id){
Make.findById(req.query.id,function(err,foundMake){
console.log("found the query string");
selectedMake = foundMake;
console.log(selectedMake);
})
}
res.render("vehicles/newvehiclemake",{makes:result,selected: selectedMake});
}
})
});
以下是我试图在我的.ejs文件中访问变量“selected”的代码
<div class="row">
<div class="col-md-9 col-md-offset-3">
<table class="table table-striped">
<tr>
<th>Available Models</th>
</tr>
<% if(selected) { %>
<% selected.models.forEach(function(model){ %>
<tr><td><%= model.name %></td></tr>
<% }) %>
<% }else { %>
<tr><td>No Models available for the selected Make</td></tr>
<% } %>
</table>
</div>
</div>
永远不会到达应该执行选定的分支,并且我总是为所选的Make
获得No Models任何线索?
答案 0 :(得分:0)
我认为这是因为您的Make.findById
方法是asynchronous来电。因此,在function(err,foundMake)
res.render
将渲染调用移动到回调函数中,然后它应该可以工作。
if(req.query.id){
Make.findById(req.query.id,function(err,foundMake){
console.log("found the query string");
selectedMake = foundMake;
// after the findById call finished, now it has value.
console.log(selectedMake);
// res.render should be called at this moment.
res.render("vehicles/newvehiclemake",{makes:result,selected: selectedMake});
})
// you would see this line is called before the data is ready.
console.log(selectedMake);
}