【问题标题】:Cannot read property items of null无法读取 null 的属性项
【发布时间】:2021-08-20 11:14:15
【问题描述】:

我正在学习 javascript 和数据库,所以我正在通过制作待办事项列表应用程序来练习。在列表中动态添加项目。列表是通过 URL 创建的,例如 http://localhost:3000/work 创建一个工作列表,但是每当我尝试添加某些内容时,它都会显示错误。

我的 JS 代码:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/todolistDB", {useNewUrlParser: true, useUnifiedTopology: true });

const itemsSchema = {
  name: String
};

const Item = mongoose.model ("Item", itemsSchema);

const item1 = new Item ({
  name: "item1"
});

const item2 = new Item ({
  name: "item2"
});

const item3 = new Item ({
  name: "item3"
});

const defaultItems = [item1, item2, item3];

const listSchema = {
  name: String,
  items: [itemsSchema]
};

const List = mongoose.model("List", listSchema);

app.get("/", function(req, res) {
  Item.find({}, function(err, foundItems){
    if(foundItems.length === 0){
      Item.insertMany(defaultItems, function(err){
        if(err){
          console.log(err);
        } else {
          console.log("Succesfully saved the items");
        }
      });
      res.redirect("/");
    } else {
      res.render("list", {listTitle: "Today", newListItems: foundItems});
    }
  });
});

app.get("/:customListName", function(req, res){
  const customListName = req.params.customListName;
  List.findOne({name: customListName}, function(err, foundList){
    if(!err){
      if(!foundList){
        //Create a new list
        const list = new List({
          name: customListName,
          items: defaultItems
        });
        list.save();
        res.redirect("/" + customListName);
      } else{
        //show the existing list
        res.render("list", {listTitle: foundList.name, newListItems: foundList.items})
      }
    }
  });
});

app.post("/", function(req, res){
  const itemName = req.body.newItem;
  const listName = req.body.list;
  const item = new Item ({
    name: itemName
  });

  if(listName === "Today"){
    item.save();
    res.redirect("/");
  } else {
    List.findOne({name: listName}, function(err, foundList){
      if(err){
        console.log(err);
      } else{
        foundList.items.push(item);
        foundList.save();
        res.redirect("/" + listName);
      }
    });
  }
});

app.post("/delete", function(req, res){
  const checkedItemId = req.body.checkbox;
  Item.findByIdAndRemove(checkedItemId, function(err){
    if(!err){
      console.log("Succesfully deleted the item!!");
      res.redirect("/");
    }
  });
});

app.get("/about", function(req, res){
  res.render("about");
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

我的 ejs 代码:

<%- include("header") -%>

  <div class="box" id="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" name="newItem" placeholder="New Item" autocomplete="off">
        <button type="submit" name="list" value="<%=listTitle%>">+</button>
      </form>
  </div>

<%- include("footer") -%>

【问题讨论】:

标签: javascript node.js database mongodb express


【解决方案1】:

List.findOne 函数可能返回一个“列表”{ name: String, items: [itemsSchema]} 项或null。不幸的是,如果尚未在您的数据库中创建此列表,您不会检查可能发生的 null 条件。

要解决此问题,您需要在代码中为 foundList 变量添加存在性检查。

如果foundList 变量不为空,则foundList 包含一个列表,并且可以将新项目推送到该列表。 否则,如果 foundList 变量为空,您可以使用此名称和要添加的项目创建一个新列表。

if (err) {
    console.log(err);
} else if (foundList !== null) {
    foundList.items.push(item);
    foundList.save();
    res.redirect("/" + listName);
} else {
    // List is not found, here you can create a new list with the item, or possibly return an error to the user (listName not found!)
    foundList = new List({ foundList: [item], name: listName });
    foundList.save();
    res.redirect("/" + listName);
}

PS:你可以重构我上面写的代码来减少重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2016-11-24
    • 2012-04-29
    相关资源
    最近更新 更多