如何在猫鼬上链接文档

时间:2019-12-20 11:22:14

标签: express mongoose

我是新来表达发展的人,我正在尝试建立一个博客。我建立了两个模型,一个用于发布,一个用于使用。在用户架构上,我有一个属性帖子,可在用户创建帖子时保存该帖子。在控制器上,在我创建帖子之前,我先从req.params中获取用户的ID,然后再通过findbyid函数检索用户,然后尝试将帖子保存在用户的posts属性中,但是没有成功。

const mongoose = require("mongoose");

UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    posts: [{type: mongoose.Schema.Types.ObjectId, ref: "Post"}]
})

module.exports = mongoose.model("User", UserSchema);
const Post = require("../model/post");
const User = require("../model/user");

module.exports = {
    new: (req, res) => {
        res.render("new_post");
    },
    post_new: (req, res) => {
        const title = req.body.title;
        const article = req.body.article;
        const id = req.params.id;

        const post = new Post({
            title: title,
            article: article, 
        })

        User.findById(id)
        .then(user => {
            user.posts.push(post);
        })

        //post.created_by.push(id);

        post.save()
        .then(result => {
            console.log("Post has created");
            res.redirect("/");
        });
    }
};

1 个答案:

答案 0 :(得分:0)

我看到了一些问题。

您的user模式不应包含posts的数组。相反,您的post模式应该具有一个名为user / userId的字段来存储用户ID。 示例:

const PostSchema = new mongoose.Schema({
  title: { type: String },
  ....,
  userId: {type: mongoose.Schema.Types.ObjectId, ref: "User"}
});

现在您的post_new函数应该是这样的。

post_new: async (req, res) => {
  const title = req.body.title;
  const article = req.body.article;
  const id = req.params.id;

  const post = await Post.create({
      title: title,
      article: article,
      userId: id
  });

  console.log("Post has created");
  res.redirect("/");
}

如果您想坚持自己的方式,那么create_new函数应该像这样。

post_new: async (req, res) => {
  const title = req.body.title;
  const article = req.body.article;
  const id = req.params.id;

  const post = new Post({
      title: title,
      article: article, 
  });

  const {_id} = await post.save();

  const user = await User.findById(id);
  user.posts.push(_id);
  await user.save();

  console.log("Post has created");
  res.redirect("/");
}