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