【发布时间】:2021-09-08 03:19:54
【问题描述】:
我创建了一个评论系统。我可以发表评论(创建新评论)一次。当我尝试在同一个帖子上创建另一个评论时,它会出错。请帮帮我。
我第二次尝试在 postman 上创建新评论时收到的错误消息
{
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"keyPattern": {
"title": 1
},
"keyValue": {
"title": null
}
}
后模型
//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"
用户模型
//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"
评论模型
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"
评论路线路径
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)
}
})
【问题讨论】:
-
正如错误所说,这是关于
PostSchema标题中的重复键错误,值为空,这意味着您有一个标题为空的帖子。也许await currentPost.save()导致了错误,也许你应该使用update和$pull而不是save。 docs.mongodb.com/manual/reference/operator/update/pull -
感谢您的帮助。你能帮我解释一下吗?
-
我自己没有遇到过这个问题,这只是我根据你的 Mongoerror 的猜测,但我猜这个链接与你的问题有关stackoverflow.com/questions/24430220/…
标签: node.js mongodb express mongoose