Mongoose移除insertMany/find回调后,待办应用代码问题咨询
代码中的潜在问题及修正方案
一、Node.js代码核心问题
- 未定义变量的引用错误
const defaultItems = [study, practice, eat];里的study、practice、eat是未声明的变量,运行时会抛出ReferenceError。结合EJS模板中使用item.name的逻辑,这些元素应该是包含name字段的对象,正确写法应为:
const defaultItems = [ { name: "study" }, { name: "practice" }, { name: "eat" } ];
- 完全忽略数据库查询结果
Item.find().then(function(){的回调函数没有接收查询结果参数,导致根本无法获取数据库中存储的待办项数据。正确写法需要接收查询返回的结果:
Item.find().then(function(foundItems) { // 后续逻辑基于foundItems处理 })
错误的触发插入逻辑的判断条件
当前代码通过defaultItems.length === 0判断是否插入数据,这是在检查本地数组的长度,而非数据库中是否存在数据。实际应该判断查询到的foundItems.length === 0,否则不管数据库有没有数据,都会直接渲染本地数组,完全违背了用数据库存储数据的初衷。异步操作顺序混乱
调用Item.insertMany()后直接执行res.redirect("/"),此时插入操作可能还未完成(异步操作未结束),会导致跳转后的请求无法查询到刚插入的数据。必须把res.redirect("/")放在insertMany的then回调内部,确保数据插入完成后再跳转:
Item.insertMany(defaultItems) .then(function() { console.log("Added successfully!"); res.redirect("/"); // 移到此处保证异步操作完成后跳转 }) .catch(function(err) { console.log(err); });
- 渲染数据源错误
else分支中渲染的是本地的defaultItems,而非数据库查询到的foundItems,导致页面展示的始终是初始本地数据,无法展示数据库中新增的待办项。正确应传入数据库查询结果:
res.render("list", { listTitle: "Today", newListItems: foundItems });
二、EJS代码潜在问题
当newListItems为空数组或非数组类型时,forEach会抛出错误。建议添加存在性判断避免报错:
<% if (newListItems && newListItems.length > 0) { %> <% newListItems.forEach(function(item){ %> <div class="item"> <input type="checkbox"> <p> <%= item.name %> </p> </div> <% }); %> <% } %>
修正后的完整Node.js代码
const defaultItems = [ { name: "study" }, { name: "practice" }, { name: "eat" } ]; app.get("/", function(req, res) { Item.find() .then(function(foundItems) { if (foundItems.length === 0) { Item.insertMany(defaultItems) .then(function() { console.log("Added successfully!"); res.redirect("/"); }) .catch(function(err) { console.log(err); }); } else { res.render("list", { listTitle: "Today", newListItems: foundItems }); } }) .catch(function(err) { console.log(err); }); });
内容的提问来源于stack exchange,提问作者UltimateKaycee
相关产品推荐
相关产品推荐

