im trying to populate an array from mongoDB
userSchema :
var campgroundSchema = new mongoose.Schema({
title: String,
image: String,
description: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}]
});
module.exports = mongoose.model("Campground", campgroundSchema);
and the showRoute :
app.get("/campgrounds/:id", function (req, res) {
Campground.findById(req.params.id).populate("comments").exec(function (err, foundCamp) {
if (err) {
console.log(err);
} else {
res.render("show", {
campground: foundCamp
});
}
});
});
when i execute the code above i get the following error: "Cannot read property 'title' of null"
however when i didn't use ".populate()" the code run with no problems but the comments array was still just an array of ids
//app.get("/campgrounds/:id", function (req, res) {
// Campground.findById(req.params.id, function (err, foundCamp) {
// if (err) {
// console.log(err);
// } else {
// res.render("show", {
// campground: foundCamp
// });
// }
// });
//});
also this is the show.ejs template :
<div class="container">
<div class="content">
<h1>
<%= campground.title %>
</h1>
<img src="<%= campground.image %>">
<p>
<%= campground.description %>
</p>
</div>
</div>
via Iskandar
No comments:
Post a Comment