猫鼬-如何检查用户是否是发布帖子的用户

时间:2019-06-30 10:56:36

标签: javascript node.js mongodb mongoose ejs

所以基本上,问题是,我想找出如何检查用户是否是撰写该帖子的用户,如果是该用户,因为他是我想显示编辑按钮和删除按钮?是创建它的人,但如果没有创建该按钮,则我不希望显示这些按钮,因为我不希望不是自己创建帖子的用户删除或编辑其他人的帖子。

一些重要的代码:

model.js

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
}

post.ejs

    <main class="post-detail">
        <h1><%= post.title %></h1>
        <h2><%= post.description%></h2>
        <p><%= post.context%></p>

        <% if (post.author === user) { %>
        <a href="/posts/edit-post/<%= post._id %>">Edit Post</a>
        <a href="/posts/deleted-post/<%= post._id %>">Delete Post</a>
        <% } %>
    </main>

管理控制器中的导出功能

exports.getPost = async (req, res) => {
    try {
        const post = await Post.findById(req.params.postId);
        const user = await User.findOne({_id: req.user});

        res.render("admin/post", {
            post: post,
            pageTitle: post.title,
            path: "/posts",
            user: user
        })

    } catch (err) {
        console.log(err);
    }

}

这是另一个导出的函数,在该函数中,仅当用户是该帖子的作者时,我才尝试获取该帖子,因为该用户指向myposts页面

exports.getMyPostsPage = async (req, res) => {
    const posts = await Post.find({
        author: req.user
    })

    res.render("admin/myposts", {
        path: "/myposts",
        pageTitle: "My Posts",
        posts: posts
    })
}

0 个答案:

没有答案