Angela Yu课程中Mongoose待办清单遇数组未定义TypeError问题
解决TypeError: Cannot read properties of undefined (reading 'length')问题
错误原因
你在Item.find({}).then()的回调参数顺序错误。Mongoose的find方法Promise回调中,第一个参数是错误对象,第二个才是查询结果。当前写法把err放在第一位,foundItems第二位,一旦查询出错,foundItems就会是undefined,访问foundItems.length就会触发报错。
修正步骤
调整find回调的参数与错误处理逻辑
改用.then()接收查询结果,.catch()捕获错误,修正后的首页路由代码:app.get("/", function(req, res) { Item.find({}) .then(function(foundItems) { if(foundItems.length === 0) { Item.insertMany(defaultItems) .then(function() { console.log("Successfully saved default items to DB!"); console.log(defaultItems); // 修正拼写错误:defautItems → defaultItems res.redirect("/"); }) .catch(function(err) { console.log(err); }); } else { res.render("list", {listTitle: "Today", newListItems: foundItems}); console.log(foundItems); } }) .catch(function(err) { console.log("查询数据出错:", err); }); });修正拼写错误
原代码中console.log(defautItems);存在拼写错误,改为defaultItems。修复post路由的无效代码
app.post("/")里的[enter image description here](https://i.sstatic.net/C2viu.png)是输入垃圾内容,删除后修正:app.post("/", function(req, res){ const itemName = req.body.newItem; const item = new Item({ name: itemName }); item.save() .then(function() { res.redirect("/"); }) .catch(function(err) { console.log(err); }); });处理未定义的workItems变量
app.get("/work")中用到的workItems未定义,会引发新错误。如果需要实现工作清单功能,可以参考主清单的Mongoose查询逻辑,创建对应的集合或文档。
内容的提问来源于stack exchange,提问作者Rhedac
相关产品推荐
相关产品推荐

