【发布时间】:2020-10-24 06:18:27
【问题描述】:
我仍然是网络开发的婴儿。我收到以下错误,可以 有人帮我吗?
架构:
var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String,
_id: String
});
var Campground = mongoose.model("Campground", campgroundSchema);
app.get("/campgrounds/:id",function(req , res){
Campground.findById(req.params.id, function(err, foundCampgrounds){
if(err){
console.log(err);
}else{
res.render("show", {campground: foundCampgrounds});
}
});
});
这是 index.ejs 模板:
<div class="row text-center" style="display:flex; flex-wrap:wrap">
<% campgrounds.forEach(function(campground){ %>
<div class="col-md-3 col-sm-6">
<div class="thumbnail">
<img src="<%= campground.image %>">
<div class="caption">
<h4> <%= campground.name %> </h4>
</div>
<p><a href="/campgrounds/ <%= campground._id %>"
class="btn btn-primary">More Info</a>
</p>
</div>
</div>
<% }) %>
</div>
show.ejs:
<%- include('partials/header')%>
<h1>this is a show template</h1>
<p><%= campground.name %></p>
<%- include('partials/footer')%>
类型错误:
Cannot read property 'name' of null
【问题讨论】:
-
你能在你
res.render(..)页面的地方添加nodejs-code吗? -
不确定我是否理解您的问题?
-
您必须检查 foundCampgrounds 是否存在。 Mongoose
findById如果找不到您的记录,请返回undefined。您可以使用:if (foundCampgrounds) { ... }
标签: node.js express mongoose mongodb-query