【发布时间】:2019-11-12 10:02:32
【问题描述】:
所以基本上我看不到我所做的评论,只有在我创建评论之后,当我再次渲染同一页面时,我才能看到评论及其作者,但如果我看不到它,例如,转到帖子或我的帖子页面,然后我 GET 到我创建评论的同一个帖子,那是评论不再可见的时候。请帮助我,如果我在离开该页面后再次尝试 GET 到同一个帖子,我不知道为什么评论不再可见。
如果你对我有任何想法,我应该如何创建和制作我的评论模型,请帮助我:)
model.js
const mongoose = require("mongoose"),
Schema = mongoose.Schema,
bcrypt = require("bcryptjs");
const commentSchema = new Schema({
context: String,
author: String,
postId: {
type: Schema.Types.ObjectId
}
})
const postSchema = new Schema({
title: String,
description: String,
context: String,
author: {
type: Schema.Types.ObjectId,
},
comments: [commentSchema]
});
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true
},
posts: [postSchema]
});
userSchema.pre("save", async function save(next) {
const user = this;
if (!user.isModified("password")) return next();
const hashedPassword = await bcrypt.hash(user.password, 10);
user.password = hashedPassword;
next();
});
const Post = mongoose.model("Post", postSchema);
const User = mongoose.model("User", userSchema);
const Comment = mongoose.model("Comment", commentSchema)
module.exports = {
User,
Post,
Comment
}
管理员控制器
exports.postCreateComment = async (req, res) => {
const {
context
} = req.body;
try {
const post = await Post.findById(req.params.postId);
const comment = new Comment({
context: context,
author: req.user.name,
postId: post._id
});
const savedComment = await comment.save();
const postsComment = await post.comments.push(comment);
res.render("admin/post", {
path: "/posts",
pageTitle: post.title,
post: post,
});
} catch (error) {
console.log(error);
}
}
管理路线
router.post("/posts/:postId", adminController.postCreateComment);
<main class="post-detail">
<h1><%= post.title %></h1>
<h2><%= post.description%></h2>
<p><%= post.context%></p>
<% if(String(post.author) === String(user._id)) { %>
<a href="/posts/edit-post/<%= post._id %>">Edit Post</a>
<a href="/posts/deleted-post/<%= post._id %>">Delete Post</a>
<% } %>
</main>
<div class="create-comment">
<form action="/posts/<%=post._id%>" method="POST">
<label for="comment">Comment Here</label>
<textarea name="context" placeholder="Enter Comment..." cols="30" rows="10"></textarea>
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit">Submit</button>
</form>
</div>
<% if (post.comments.length > 0) { %>
<% for (let comment of post.comments) { %>
<div class="comment">
<div>
<article>
<h1><%=comment.author%></h1>
<p><%=comment.context%></p>
</article>
</div>
</div>
<% } %>
<% } %>
【问题讨论】:
标签: javascript node.js mongodb mongoose ejs