我想检查帖子是否属于创建它的用户

时间:2019-06-30 16:01:16

标签: javascript node.js mongodb mongoose ejs

基本上,我想检查帖子是否属于用户,一切似乎都很好,但是仍然无法正常工作。我检查了该用户的ID是否与该帖子的作者相同,是的,但它仍然不起作用,而是显示了myposts页面上的所有帖子,这些帖子甚至是由不同的用户创建的。我不知道该怎么办。

管理员控制器

exports.getMyPostsPage = async (req, res) => {

    const posts = await Post.find({author: req.user._id})
    console.log(req.user._id);
    console.log(posts);
    res.render("admin/myposts", {
        path: "/myposts",
        pageTitle: "My Posts",
        posts: posts,
    })
}

模型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
}

myposts.ejs

    <main>
        <% if (posts.length > 0) { %>

        <% for (let post of posts) { %>

        <div class="grid">
            <div>
                <article class="post">
                    <h1><%=post.title%></h1>
                    <p><%=post.description%></p>
                    <a href="/posts/<%=post._id%>">See Post</a>
                    <article>
            </div>

        </div>


        <% } %>
        <%  } else { %>

        <h1 class="no-post">You have no Posts</h1>
        <% } %>
    </main>

0 个答案:

没有答案