猫鼬-如何检查现有用户?

时间:2019-06-25 20:17:23

标签: javascript mongodb mongoose model ejs

在“获取帖子”页面上,我如何检查现有的帖子,然后我还要确保用户可以在那里查看这些帖子,但是我将如何去做,检查现有的帖子,然后确保我可以访问其属性(例如标题和描述),以便将它们用作渲染中的术语。

admin js控制器


exports.getPostsPage = (req, res) => {
    Post.find()
    res.render("admin/posts", {
        path: "/posts",
        pageTitle: "Posts",
        title: post.title,
        description: post.description
    });
}

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)
        res.render("admin/posts", {
            pageTitle: "Posts",
            path: "/posts",
            title: post.title,
            description: post.description,

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

}

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
}

0 个答案:

没有答案