Express 如何链接mongoose上的文档

Express 如何链接mongoose上的文档,express,mongoose,Express,Mongoose,我是一个新的表达发展,我正试图建立一个博客。我建立了两个模型,一个用于发布,一个用于使用。在用户模式上,我有一个属性posts,当用户创建帖子时,可以保存帖子。在控制器上,首先在创建帖子之前,我从req.params获取用户id,然后通过findbyid函数检索用户,并尝试在用户的posts属性上保存帖子,但没有成功 const mongoose = require("mongoose"); UserSchema = new mongoose.Schema({ name: {

我是一个新的表达发展,我正试图建立一个博客。我建立了两个模型,一个用于发布,一个用于使用。在用户模式上,我有一个属性posts,当用户创建帖子时,可以保存帖子。在控制器上,首先在创建帖子之前,我从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);
我看到一些问题

您的
用户
架构不应该有
帖子的数组
。相反,您的
post
模式应该有一个名为
user
/
userId
的字段来存储用户ID。 例如:

现在,您的
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("/");
}
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("/");
}
如果您想坚持自己的方式,那么
create\u 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("/");
}
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("/");
}

你说不成功是什么意思?您面临的问题/错误是什么?post是否未保存在数据库中?是。帖子不保存在用户属性的帖子中