我正在观看有关创建宁静应用程序的教程。我尝试了自己的项目,该项目与本教程稍有不同,但现在我陷入了困境。我正在尝试将我的评论集合与Blog集合相关联,但是数据没有显示在我的显示页面上。我很难弄清楚为什么我的评论未显示在我的博客文章中。
app.js文件
var bodyParser = require('body-parser'),
methodOverride = require('method-override'),
expressSanitizer = require("express-sanitizer"),
mongoose = require('mongoose'),
express = require('express'),
app = express(),
Blog = require("./models/blog"),
Comment = require('./models/comment'),
seedDB = require("./seeds");
seedDB();
//APP CONFIG
mongoose.connect("mongodb://localhost:27017/blogApp", { useNewUrlParser: true
);
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressSanitizer());
app.use(methodOverride("_method"));
// SHOW Route
app.get("/blog/:id", function (req, res) {
Blog.findById(req.params.id).populate("Comments").exec(function (err, foundBlog) {
if (err) {
console.log(err);
res.redirect("/blog");
} else {
console.log(foundBlog);
res.render("show", { blog: foundBlog });
}
});
});
种子文件
var mongoose = require("mongoose")
var Blog = require("./models/blog");
var Comment = require("./models/comment")
function seedDB() {
Blog.remove({}, function (err) {
if (err) {
console.log(err);
} else {
console.log("Removed Blogs");
}
data.forEach(function (seed) {
Blog.create(seed, function (err, blog) {
if (err) {
console.log(err)
} else {
console.log("blog created");
Comment.create(
{
text: "That was one great blog post",
author: "Homer"
}, function (err, comment) {
if (err) {
console.log(err)
} else {
blog.comments.push(comment);
comment.save();
console.log("created new comment");
}
}
)
}
})
});
});
}
评论模型
var mongoose = require("mongoose");
var commentSchema = new mongoose.Schema({
text: String,
author: String
})
var Comment = mongoose.model("Comment", commentSchema);
module.exports = Comment
博客模型
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: { type: Date, default: Date.now },
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
})
var Blog = mongoose.model("Blog", blogSchema);
module.exports = Blog
在我的show.ejs页面上,这是我的代码,用于尝试显示注释,但没有填充
<% blog.comments.forEach(function(comment){ %>
<p><strong><%= comment.author %></strong> - <%= comment.text %> </p>
<% }) %>
这是我在show route中来自console.log的结果
{ comments: [],
_id: 5b666ed86feec81af8651b9b,
title: 'Test Blog 2',
image: 'https://images.unsplash.com/photo-1499938971550-7ad287075e0d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=d787d5e47840a5a0a6ff7574c90a02d7&auto=format&fit=crop&w=500&q=60',
body: 'Hello this is a blog post',
created: 2018-08-05T03:28:24.404Z,
__v: 0 }
请帮助我弄清楚为什么不显示评论
答案 0 :(得分:0)
我认为问题在于这条线
Blog.findById(req.params.id).populate("Comments").exec(function (err, foundBlog)
应改为populate("Comments")
而不是populate("comments")
尝试通过上述更改执行一次。