reactjsmongodbapimongoosemern

MERN Stack User create Post Mongoose MongoError : 11000


I was developing a Mini Twitter App to Test MERN Stack, and it was working great untill this error. I just want to have a User Model and Post Model (Users can post and like posts).

USER MODEL

   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);

POST MODEL

    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);

So, the first post is succesfully created, but when I try to post another, error 500 is shown.

createPost Controller

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 });
  }
}

As I said, it worked OK till this, I know I touched something and broke everything but I dont know what. Any tips? ty :D


Solution

  • Since User.posts is an array of refs you should just push the 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 });
      }
    }