【发布时间】:2020-07-22 11:10:54
【问题描述】:
我已尝试多次重新启动服务器。我还删除了节点模块并再次安装。我还清除了缓存并多次重新启动 VS 代码。似乎没有任何工作。现在在写foundList.items.push(item); 之后,我也无法将项目添加到我的路由目录中。在此之前,我能够从路由目录中添加或删除项目。谁能帮我解决这个问题?
这是我的 Express 代码:
app.post("/", function (req, res) {
const itemName = req.body.newItem;
const listName = req.body.list;
const item = new Item({
name: itemName,
});
//Check id the user tried to add the list is default list or the custom list. Then find the custom list and add the new item and redirect to the custom list i.e ///listName
if (listName === "Today") {
item.save();
res.redirect("/");
} else {
List.findOne({ name: listName }, function (err, foundList) {
foundList.items.push(item);
foundList.save();
res.redirect("/" + listName);
});
}
});
这也是我的 EJS 代码。
<div class="box heading">
<h1><%= listTitle %></h1>
</div>
<div class="box">
<% newListItems.forEach(function(item) { %>
<form action="/delete" method="POST">
<div class="item">
<input
type="checkbox"
name="checkbox"
value="<%= item._id %>"
onChange="this.form.submit()"
/>
<p><%=item.name%></p>
</div>
</form>
<%});%>
<form class="item" action="/" method="post">
<input
type="text"
placeholder="newItem"
name="newItem"
autocomplete="off"
/>
<button type="submit" name="button" value="<%= listTitle %>">+</button>
</form>
</div>
【问题讨论】:
-
如果
foundList为空,err可能已设置。如果在尝试使用foundList之前已设置,请尝试检查并抛出err。 -
foundList 不为空。它说无法读取 null 的属性“项目”。
-
程序中唯一读取
.items属性的行是:foundList.items。因此,如果这不是崩溃线,请发布minimal reproducible example。 -
是的,这就是崩溃线。我已经尝试了所有我能找到的选项。仍然无法解决。我仍然收到一条错误消息,提示“无法读取 null 的属性 'items'”
-
我不知道还能说什么——如果
foundList为空,尝试执行null.items会引发错误。当设置err时,这意味着您尝试运行的查询失败,您应该抛出它或者不 访问foundList.items。相反,无论是否设置了err,代码都会愉快地忽略err并直接索引到.items。if (err) throw err;应该在foundList.items之前。
标签: node.js express mongoose ejs