【发布时间】:2021-09-09 03:49:27
【问题描述】:
我在这方面已经很久了。我似乎无法在任何地方找到解决方案。我正在使用 Node、expressjs 和 mongodb 开发一个博客应用程序。我创建了一个评论系统,用户可以在其中评论个人博客文章。问题是用户只能发表一条评论。如果他们再次尝试发表评论,我会得到一个 mongodb 错误。这是错误:
"name": "MongoError",
"index": 0,
"code": 11000,
"keyPattern": {
"title": 1
},
"keyValue": {
"title": null
}
}
我感觉到错误来自我的 Post 架构模型。代码如下:
//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"
这是我的评论模型
const mongoose = require("mongoose"); //import mongoose to be used
const Schema = mongoose.Schema;
const CommentSchema = new mongoose.Schema(
{
description:{
type: String,
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"
这是我的评论创建新评论代码:
/creating catergory logic
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.findByIdAndUpdate(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)
}
})
【问题讨论】:
-
能否提供
req.body添加cmets -
感谢您帮助我。添加评论的代码是我用粗体标题发布的代码:“这是我的评论,创建新的评论代码:”
-
记下你的json请求代码
-
我真希望我知道你在问我什么。其实我还在学习的路上。请帮我更好地解释你问我的问题。提前致谢。
-
router.post ,console.log(req.body) 后提供