mongodb MERN Stack User create Post Mongoose MongoError:11000

ykejflvf  于 2023-03-29  发布在  Go
关注(0)|答案(1)|浏览(140)

我正在开发一个迷你Twitter应用程序来测试MERN堆栈,它一直工作得很好,直到这个错误.我只是想有一个用户模型和帖子模型(用户可以发布和喜欢的帖子).

用户型号

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。

createPost控制器

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

fcwjkofz

fcwjkofz1#

因为User.posts是一个refs数组,所以你应该只推送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 });
  }
}

相关问题