类型错误:无法使用 nodejs 在 monogdb 中读取 null 的属性“items" [英] TypeError: Cannot read property 'items' of null in monogdb using nodejs
问题描述
我正在创建一个待办事项列表应用程序,它动态添加项目并通过 url 动态创建列表.例如:http://localhost:3000/Home 将创建一个主页"列表和 http://localhost:3000/Work 将创建带有一些预先添加的默认值的Work".但是当我通过像这样的网址:http://localhost:3000/Home 并添加新项目,然后它引发错误.
下面是我的 app.js 代码
//jshint esversion:6const express = require("express");const bodyParser = require("body-parser");const mongoose=require("mongoose");const app = express();app.set('视图引擎', 'ejs');app.use(bodyParser.urlencoded({extended: true}));app.use(express.static("public"));mongoose.connect("mongodb://localhost:27017/todolistDB",{ useNewUrlParser:true , useUnifiedTopology: true });const itemsSchema={名称:字符串};const Item=mongoose.model("Item",itemsSchema);const item1=新项目({名称:欢迎使用您的待办事项列表"});const item2=新项目({name:"点击+按钮添加新项目"});const item3=新项目({名称:<-- 点击这里删除一个项目"});const defaultItems=[item1,item2,item3];const listSchema={名称:字符串,项目:[项目架构]};const List=mongoose.model("List",listSchema);app.get("/", function(req, res) {//使用 mongoose 查找元素并检查数组是否为空然后添加项目.//如果数组已包含项目,则在启动服务器多次时,数组不会再次添加相同的项目.Item.find({},function(err,foundItems){如果(foundItems.length===0){Item.insertMany(defaultItems,function(err){如果(错误){控制台日志(错误);} 别的 {console.log("保存成功.....");}});res.redirect("/");} 别的 {res.render("list", {listTitle: "Today", newListItems: foundItems});}});});app.post("/", function(req, res){const itemName = req.body.newItem;const listName=req.body.list;const 项目=新项目({名称:项目名称});if(listName==="今天"){item.save();res.redirect("/");}别的{List.findOne({name:listName},function(err,foundList){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){如果(错误){控制台日志(错误);} 别的 {console.log("选中的项目删除成功");res.redirect("/");}});});//app.get("/work", function(req,res){//res.render("list", {listTitle: "Work List", newListItems: workItems});//});app.get("/:customListName",function(req,res){const customListName=req.params.customListName;控制台日志(自定义列表名称);List.findOne({name:customListName},function(err,foundList){如果(!错误){如果(!找到列表){//创建一个新列表const 列表=新列表({名称:自定义列表名称,项目:默认项目});list.save();res.redirect("/"+customListName);}别的{//显示现有列表res.render("list",{listTitle:foundList.name,newListItems:foundList.items});}}});});app.get("/about", function(req, res){res.render("关于");});app.listen(3000,函数(){console.log("服务器在 3000 端口启动");});
list.ejs 的代码
<%- include("header") -%><div class="box" id="heading"><h1><%=列表标题%>
<div class="box"><% newListItems.forEach(function(itemName){%><form action="/delete" method="post"><div class="item"><input type="checkbox" name="checkbox" value="<%= itemName.id %>"onChange="this.form.submit()"><p><%= itemName.name %></p>
</表单><%})%><form class="item" action="/" method="post"><input type="text" name="newItem" placeholder="New Item" autocomplete="off"><button type="submit" name="list" value="<%= listTitle %> ">+</button></表单>
<%- include("footer") -%>
请问有什么解决办法吗?
似乎您的 ejs 代码传递了带有额外空间的值,而 mongoose findOne 函数无法进行比较,因此它在回调函数中将空值作为参数传递..因此,更改您的邮政路线中的一行将解决该问题.const listName = req.body.list.slice(0,-1);//用于删除额外的空格
.希望这能解决您的问题.
I am creating a todo list app , which adds items dynamically and creates list dynamically through url. For example : http://localhost:3000/Home will create a "Home" list and http://localhost:3000/Work will create "Work" with some default values pre-added. But when i go through url like : http://localhost:3000/Home and add new item , then it throws an error.
Below is my code for app.js
//jshint esversion:6
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:"Welcome to your todolist"
});
const item2=new Item({
name:"Hit the + button to add new item"
});
const item3=new Item({
name:"<-- Hit this to delete an item"
});
const defaultItems=[item1,item2,item3];
const listSchema={
name:String,
items:[itemsSchema]
};
const List=mongoose.model("List",listSchema);
app.get("/", function(req, res) {
// finding elements using mongoose and to check if array is empty then add items.
// if array already contains items then array does not add same items again when starting server mupltipe times.
Item.find({},function(err,foundItems){
if (foundItems.length===0) {
Item.insertMany(defaultItems,function(err){
if (err) {
console.log(err);
} else {
console.log("Saved Successfully.....");
}
});
res.redirect("/");
} else {
res.render("list", {listTitle: "Today", newListItems: foundItems});
}
});
});
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){
foundList.items.push(item); **// NODE SHELL SHOWING ERROR IN THIS LINE**
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(err);
} else {
console.log("Selected item deleted successfully");
res.redirect("/");
}
});
});
// app.get("/work", function(req,res){
// res.render("list", {listTitle: "Work List", newListItems: workItems});
// });
app.get("/:customListName",function(req,res){
const customListName=req.params.customListName;
console.log(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 an existing list
res.render("list",{listTitle:foundList.name,newListItems:foundList.items});
}
}
});
});
app.get("/about", function(req, res){
res.render("about");
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
Code for list.ejs
<%- include("header") -%>
<div class="box" id="heading">
<h1> <%= listTitle %> </h1>
</div>
<div class="box">
<% newListItems.forEach(function(itemName){ %>
<form action="/delete" method="post">
<div class="item">
<input type="checkbox" name="checkbox" value="<%= itemName.id %>" onChange="this.form.submit()">
<p><%= itemName.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") -%>
Any solution please ?
Seems like your ejs code passes values with extra space and mongoose findOne function is not able to compare so it passes null value as a parameter in the callback function.
. So changing one line in your post route will fix the issue.
const listName = req.body.list.slice(0,-1); //for removing an extra space
.
Hope this will fix your issue.
这篇关于类型错误:无法使用 nodejs 在 monogdb 中读取 null 的属性“items"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!