首页 > 解决方案 > 如何解决这个 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)
 }
 })

标签: node.jsmongodbmongoose

解决方案


所以,我最终解决了这个问题。发生的事情是我最初在我的评论模型中创建了一个“标题”字段。后来我把它删除了。但我不知道它已经在我的Mongodb别名中被索引了。那需要手动删除。转到您的 MongoDB 集合。检查选项卡,您将看到“索引”,打开它并检查返回空错误的字段。就我而言,它是标题。我从索引菜单中删除了它,我的问题就解决了。如果您有类似的问题,您可以试试这个。


推荐阅读