2

I created a comment system. I can post the comment (create new comment) once. When I try to create another comment on the same post, it throws in error. Do help me, please.

The error message I get when I try to create new comment on postman the second time

{
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"keyPattern": {
    "title": 1
},
"keyValue": {
    "title": null
}
}

Post Model

//creating the user models for the database

   const mongoose = require("mongoose"); //import mongoose
   const Schema = mongoose.Schema;

  const PostSchema = new mongoose.Schema(
   {
   
    title:{
        type: String,
        required: true,
        unique: true,
    },
    description:{
        type: String,
        required: true, 
    },
    postPhoto:{
        type: String,
        required:false,
    },
   username:{
        type: Schema.Types.ObjectId, 
        ref: 'User'
    },
    categories:{
       type: Array,
    },
   comments: [{
         type: mongoose.Schema.Types.ObjectId,
         ref: 'Comment'
       }]
   
    }, {timestamps: true},

   );
  //exporting this schema
 module.exports = mongoose.model("Post", PostSchema); //the module name is "Post"

User model

//creating the user models for the database

  const mongoose = require("mongoose"); //import mongoose

  const UserSchema = new mongoose.Schema({

    username:{
        type: String,
        required: true,
        unique: true
    },
    email:{
        type: String,
        required: true,
        unique: true
    },
    password:{
        type: String,
        required: true
    },
    profilePicture:{
        type: String,
        default: "",
    },
  }, {timestamps: true}
 );
//exporting this schema
module.exports = mongoose.model("User", UserSchema); //the module name is "User"

Comment model

const mongoose = require("mongoose"); //import mongoose to be used
 const Schema = mongoose.Schema;

  const CommentSchema = new mongoose.Schema(
   {
    description:{
        type: Array,
        required: true, 
    },
   author:{
        type: Schema.Types.ObjectId, 
        ref: 'User'
    },
   
  postId:{
      type: Schema.Types.ObjectId, 
        ref: 'Post',
         partialFilterExpression: { postId: { $type: 'string' } }
  }
  }, {timestamps: true}
  );
  //exporting this schema
 module.exports = mongoose.model("Comment", CommentSchema); //the module name is "Post"

Comment route path

router.post("/posts/:id/comment", async (req, res) =>{
const newComment = new Comment(req.body);//we create a new comment for the database
    
try{
    const savedComment = await newComment.save();//we need to try and catch the new comment and save it

    const currentPost = await Post.findById(req.params.id)//we need to find the post that has the comment via the id
        currentPost.comments.push(savedComment)//we need to push the comment into the post

        await currentPost.save()//we saved the new post with the comment
    res.status(200).json(currentPost)
  }catch(err){
    res.status(500).json(err)
 }
  })

Screen shot of my postman setup and error as well enter image description here

kinhs
  • 175
  • 13
  • as the error says this is about a duplicate key error in the title of `PostSchema` with null value, which means you have a post with the null title. maybe the `await currentPost.save()` caused the error, maybe you should use `update` and `$pull` instead of `save`. https://docs.mongodb.com/manual/reference/operator/update/pull/ – Soroush Salehi 404 Sep 08 '21 at 06:01
  • thank you for trying to help. Could you help me explain better? – kinhs Sep 08 '21 at 10:29
  • I haven't had this problem myself, and that's just only my Guess based on your Mongoerror, but I guess this link related to your question https://stackoverflow.com/questions/24430220/e11000-duplicate-key-error-index-in-mongodb-mongoose – Soroush Salehi 404 Sep 08 '21 at 22:12

1 Answers1

0
const currentPost = await Comment.create({
        createdBy : req.params.id,
        postId:  req.params.postId,
        description,
    })

In short, everything will be carried by your URL params postman body will only be used for description body

DevArtist
  • 1
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 03 '22 at 18:39