javascript 为什么我总是得到TypeError:当我尝试从任何路由中删除项目时,无法读取null属性(阅读“items”)?

qhhrdooz  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(108)
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"));

main().catch(err => console.log(err));

async function main() {
    await mongoose.connect('mongodb://127.0.0.1:27017/todolistDB');
    
    const itemSchema = new mongoose.Schema({
        name: String
    });

    const Item = new mongoose.model("item", itemSchema);

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

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

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

    const defaultItems = [item1, item2, item3];

    const listSchema = new mongoose.Schema({
        name: String,
        items: [itemSchema]
    });

    const List = new mongoose.model("list", listSchema);
    
    app.get("/", function(request, response){
        
        Item.find({}).then(function(foundItems){
            if(foundItems.length === 0){
                Item.insertMany(defaultItems).then(function(){
                    response.redirect("/");
                });
            } else {
                response.render("list", {listTitle: "Today", newListItems: foundItems});
            }
        });
        
    });

    app.get("/:customListName", function(req, res){

        const customListName = req.params.customListName;

        const requestedUrl = req.originalUrl;
        
        if (requestedUrl === "/favicon.ico") {
            res.status(204).end(); // Skip favicon.ico requests
            return;
        }
        

        List.findOne({name: customListName}).then(function(foundList){

            if(!foundList){ //Create a new List
                const list = new List({
                    name: customListName,
                    items: []
                });

                list.save();
                res.redirect("/" + customListName);
            }
            else{
                res.render("list", {
                    listTitle: foundList.name,
                    newListItems: foundList.items,
                });
            }
        }).catch(function(error){
            console.log(error);
        });

    });

    app.post("/:customListName?", async function(req, res) {
        const customListName = req.params.customListName;
        const newItem = req.body.newItem;
      
        const item = new Item({
          name: newItem
        });
      
        if (customListName) {
            List.findOne({ name: customListName }).then(function(foundList) {
                foundList.items.push(item);
                foundList.save();
                res.redirect("/" + customListName);
            }).catch(function(error) {
                console.log(error);
            });
        }
        else {
            await item.save();
            res.redirect("/");
        }
    });

    app.post("/delete", async function(req, res) {
        const checkedItemId = req.body.checkbox;
        const listName = req.body.listName;

        console.log("checkboxID: " + checkedItemId);
      
        if (listName === "Today") {
          await Item.findByIdAndRemove(checkedItemId, function(err) {
            if (err) {
              console.log(err);
            } else {
              console.log("Successfully deleted item.");
              res.redirect("/");
            }
          });
        } else {
            List.findOne({ name: listName }, function (err, foundList) {
                if (!err) {
                    if (foundList && foundList.items) {
                            foundList.items.pull({ _id: checkedItemId });
                            foundList.save().then(() => {
                                res.redirect("/" + listName);
                            });
                    } else {
                        console.log("List or items not found.");
                        res.redirect("/" + listName);
                    }
                } else {
                    console.log(err);
                }
            });
        }
      });
      

    app.get("/about", function(request, response){
        response.render("about");
    });

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

}
<%- include("header") -%>
    
    <div class="box" id="heading">
        <h1> <%=listTitle%> </h1>
    </div>
    
    <div class="box">
        <% newListItems.forEach(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>
                <input type="hidden" name="listName" value=<%= listTitle %>>
            </form>
        <% }); %>
                    
        <form class="item" action="<%= listTitle === 'Today' ? '/' : '/' + listTitle %>" method="post">
          <input type="text" name="newItem" placeholder="New Item" autocomplete="off"><br>
          <button type="submit" name="list" value="<%= listTitle %> ">+</button>
        </form>
      
    </div>

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

rqmkfv5c1#

看起来你试图从foundList中获取item,而foundList是未定义的。
如果错误指出一个特定的行,你可以知道它是哪一个。然后确保在访问“item”之前定义了foundList
可能在这里:

else{
                res.render("list", {
                    listTitle: foundList.name,
                    newListItems: foundList.items,
                });
            }

或者这里:

if (customListName) {
            List.findOne({ name: customListName }).then(function(foundList) {
                foundList.items.push(item);
                foundList.save();
                res.redirect("/" + customListName);
            }).catch(function(error) {
                console.log(error);
            });
        }

相关问题