node.js - 如何解决这个 Mongodb“代码”:11000?
问题描述
我在这方面已经很久了。我似乎无法在任何地方找到解决方案。我正在使用 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)
}
})
解决方案
所以,我最终解决了这个问题。发生的事情是我最初在我的评论模型中创建了一个“标题”字段。后来我把它删除了。但我不知道它已经在我的Mongodb别名中被索引了。那需要手动删除。转到您的 MongoDB 集合。检查选项卡,您将看到“索引”,打开它并检查返回空错误的字段。就我而言,它是标题。我从索引菜单中删除了它,我的问题就解决了。如果您有类似的问题,您可以试试这个。
推荐阅读
- python - 并行比较两个拆分的数据列表
- bash - 运行命令以通过 bash 创建目录
- python - ElementClickInterceptedException:元素点击被拦截:
- javascript - 多个 CSS 类的每个元素的等高和窗口大小调整功能
- xml - 如何使用镜头折叠 XML 元素的节点?
- angular - 如何使用 Angular Material 让 mat-sidenav-content 占据 100% 的高度
- python - 使用指定的目标/文件名和超时时间限制将文件保存到磁盘的下载方法,无需先打开文件
- powershell - 多台 PC 上的测试路径输出不是我想要的
- python - 无法根据 url 参数在视图集自定义视图中创建记录
- ios - 使用 Flutter App 在 iOS 中未触发 UNUserNotificationCenterDelegate didReceive