events.js:288。 :无法读取null的属性“ items”

时间:2020-04-09 18:27:29

标签: node.js express mongoose ejs

我尝试过多次重启服务器。我还删除了节点模块,然后再次安装。我还清除了缓存,并多次重启了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>

1 个答案:

答案 0 :(得分:0)

看起来我正在做我的Udemy培训课程。我对编码非常陌生,花了几个小时尝试修复相同的代码。无论如何:

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