我正在开发一个网站表单,它将访问存储在 MongoDB 数据库中的信息(想象一下访问图书馆目录)。为此,我使用 NodeJS、Express、MongoDB 和带有 EJS 的视图。
代码工作正常,但如果找不到结果,我想显示错误页面或类似的内容。我已经尝试了一段时间,但我的代码似乎不起作用。
这就是我到目前为止所做的。完整的代码很长,所以我只将相关部分粘贴到我的index.js文件中:
//The querying code works, and the following two lines print the results in a view called "queryResult".
//filteredData is a filter I used to arrange the information in order.
const libraryItems = await collection.aggregate(filteredData).toArray()
res.render("queryResult", {libraryItems : libraryItems})
if(libraryItems == null){
res.render("noResults") //I created a view called noResults.ejs in the folder "views"
return
}
})
使用此代码,当查询不成功时,我会得到带有空项目列表的视图“queryResult”。我期望的是获得视图“noResults”,并显示一条消息,通知用户未找到任何结果。
我认为解决方案一定很简单,但我在编码方面不是很有经验,所以我不确定如何解决它。任何帮助将不胜感激。
您需要检查退回物品的数量。正如我所看到的,您在检查之前发送带有结果的渲染。
const libraryItems = await collection.aggregate(filteredData).toArray()
const libraryItems_count = libraryItems.length;
if(!libraryItems || libraryItems == null || libraryItems_count < 1){
res.render("noResults")
return;
}
res.render("queryResult", {libraryItems : libraryItems});