基本上是我发布创建邮政控制器时,帖子一次显示,问题是当我获得同一页面时,它显示了两次?
我该如何解决此问题,以便如果帖子已经存在,那么即使我得到页面也不应该显示另一个时间?
我的目标是在用户帖子或获取页面上,它仍然应该显示一次。
管理员控制器
const path = require('path');
const bcrypt = require("bcryptjs");
const mongoose = require("mongoose");
const _ = require("lodash");
const {
User,
Post,
} = require("../models/model");
exports.getMyPostsPage = (req, res) => {
res.render("admin/myposts", {
path: "/myposts",
pageTitle: "My Posts",
})
}
exports.getCreatepostPage = (req, res) => {
res.render("admin/createpost", {
path: "/create",
pageTitle: "Create",
});
}
exports.getPostsPage = async (req, res) => {
try {
const posts = await Post.find({})
res.render("admin/posts", {
path: "/posts",
pageTitle: "Posts",
posts: posts
});
} catch (err) {
console.log(err);
}
}
exports.postCreatePost = async (req, res) => {
const {
title,
description,
context
} = req.body;
const post = new Post({
title,
description,
context,
author: req.user
});
try {
const savedPost = await post.save()
const usersPost = await req.user.posts.push(post);
console.log(req.user.posts)
const posts = await Post.find({})
res.render("admin/posts", {
pageTitle: "Posts",
path: "/posts",
posts: posts
})
} catch (err) {
console.log(err);
}
}
posts.ejs
<%- include("../includes/head.ejs") %>
<link rel="stylesheet" href="/css/admin.css">
</head>
<body>
<%- include("../includes/navigation.ejs", ) %>
<% for (const post of posts) { %>
<div class="posts">
<form action="/post" method="POST">
<h1><%=post.title%></h1>
<p><%=post.description%></p>
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit">
See Post
</button>
</form>
</div>
<% } %>
<%- include("../includes/footer.ejs") %>
const mongoose = require("mongoose"),
Schema = mongoose.Schema,
bcrypt = require("bcryptjs");
const postSchema = new Schema({
title: String,
description: String,
context: String,
author: {
type: Schema.Types.ObjectId,
}
});
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);
module.exports = {
User,
Post
}
我在使用F5按钮时遇到了问题,它重复了帖子部分,但是现在很好,实际上这不是一个真正的问题,只是一个错误。