【问题标题】:events.js:288. :Cannot read property 'items' of null事件.js:288。 :无法读取 null 的属性“项目”
【发布时间】: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 并直接索引到.itemsif (err) throw err; 应该在 foundList.items 之前。

标签: node.js express mongoose ejs


【解决方案1】:

这看起来像是我正在做的 Udemy 培训课程。我对编码很陌生,并且花了几个小时试图修复相同的代码。总之:

尝试换行:foundList.items.push(item);单数:foundList.item.push(item);我在代码中看不到您的 listSchema。检查它,看看你是否有“项目”或“项目”。
常量列表架构 = { 名称:字符串, 项目:[项目架构] }; 我在架构中声明了项目,但在“foundList.items.push(item)”中调用项目,并且服务器一直在崩溃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2019-04-25
    • 2022-11-15
    相关资源
    最近更新 更多