MERN Stack 用户创建帖子 Mongoose MongoError:11000

问题描述 投票:0回答:1

我正在开发一个迷你 Twitter 应用程序来测试 MERN Stack,它运行良好,直到出现此错误。 我只想有一个用户模型和帖子模型(用户可以发布和喜欢帖子)。

用户模型

   import mongoose from "mongoose";

export const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, "Must enter unique Username"],
    unique: [true, "Username already exists"],
  },
  email: {
    type: String,
    required: [true, "Must enter an email"],
    unique: true,
  },
  password: {
    type: String,
    required: [true, "Must enter a password"],
    unique: false,
  },
  posts: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Post",
    },
  ],
});

export default mongoose.model.Users || mongoose.model("User", UserSchema);

后模型

    import mongoose from "mongoose";

export const PostSchema = new mongoose.Schema(
  {
    author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
    authorUsername: {
      type: String,
      required: true,
    },

    title: {
      type: String,
      required: [true, "Must enter a title"],
      trim: true,
    },
    content: {
      type: String,
      required: [true, "Must enter a content"],
      trim: true,
    },
    likes: {
      type: Array,
      required: false,
    },
  },
  { timestamps: true }
);

export default mongoose.model.Posts || mongoose.model("Post", PostSchema);

因此,第一篇文章已成功创建,但是当我尝试发布另一篇文章时,显示错误 500。

创建Post控制器

export async function createPost(req, res) {
  const { title, content, userId } = req.body;

  try {
    const user = await User.findById(userId);
    const post = new Post({
      title,
      content,
      userId,
      authorUsername: user.username,
    });
    post.author = user._id;
    user.posts.push(post);
    await post.save();
    await user.save();
    return res.status(200).json({ message: "Post created successfully", post });
  } catch (err) {
    return res.status(500).send({ message: "Error", err });
  }
}

正如我所说,到目前为止一切正常,我知道我碰了一些东西并破坏了所有东西,但我不知道是什么。 有什么建议吗?泰:D

reactjs mongodb mongoose mern
1个回答
1
投票

由于

User.posts
是一个引用数组,您应该只推送
post._id
:

export async function createPost(req, res) {
  const { title, content, userId } = req.body;

  try {
    const user = await User.findById(userId);
    const post = await Post.create({
      title,
      content,
      userId,
      authorUsername: user.username,
      author: user._id,
    });
    user.posts.push(post._id);
    await user.save();
    return res.status(200).json({ message: 'Post created successfully', post });
  } catch (err) {
    return res.status(500).send({ message: 'Error', err });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.