首页 > 解决方案 > 如何在猫鼬上链接文档

问题描述

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

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("/");
        });
    }
};

标签: expressmongoose

解决方案


我看到一些问题。

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("/");
}

推荐阅读