【问题标题】:MongoError: E11000 duplicate key error collection: myFirstDatabase.tours index: rating_1 dup key: { rating: null }MongoError:E11000 重复键错误集合:myFirstDatabase.tours 索引:rating_1 重复键:{ rating:null }
【发布时间】:2021-09-02 19:56:59
【问题描述】:

MongoError: E11000 duplicate key error collection: myFirstDatabase.tours index: rating_1 dup key: { rating: null }

当我使用邮递员创建数据时,我不明白这个错误,说 dup key: {rating:null},shcema 中没有任何评级键,这是从哪里来的?为什么我只能创建一次。

这是我的代码(tourSchema)

const mongoose = require('mongoose');

const tourSchema = new mongoose.Schema({
 name:{
    type:String, 
    required:[true, 'tour must have name'], 
    unique:true,
    trim: true
},
ratingAverage: Number,
ratingQty:Number,
discount:Number,
price:{
    type:String, 
    required:[true, 'tour must have price']
},
summary:{
    type:String, 
    required:[true, 'tour must have summary'],
    trim:true
},
description:{
    type:String, 
    trim:true
},
imageCover:{
    type:String, 
    required:[true, 'tour must have imageCover'],
    trim:true
},
images: [String],
createdAt:{
    type:Date,
    default:Date.now()
},
startDate:[Date]
})
const Tour = mongoose.model('Tour', tourSchema);

 module.exports = Tour;

这是我正在尝试添加的数据

{
"name":"the mountain explorer",
"ratingAverage":4,
"ratingQty":1,
"price":400,
"summary":"this is mountain explorer near to solua, best known for the river around it",
"description":"this mountain is located at the top of siraha mountain, has so many rivers around it",
"imageCover":"nepal_tour_cover-1.jpg",
"images":["nepal_tour-1.jpg", "nepal_tour-2.jpg", "nepal_tour-3.jpg"],
"startDate":["2020-03-12,12:44", "2020-04-12,12:54"]

}

【问题讨论】:

    标签: node.js mongodb mongoose backend


    【解决方案1】:

    您在该集合中有一个唯一的评分索引。由于您在添加时未指定评级,因此评级为空,因此您在第一次之后出现此错误。 由于您尝试添加的后续数据也没有评分,因此它们的评分为空,与索引冲突。

    首先,前往您的 mongo 控制台。

    运行此命令

    db.<collection>.getIndexes()
    

    你应该有这样的记录

    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "rating" : 1
        },
        "name" : "rating"
    }
    

    接下来,运行此命令删除索引

    db.<collection>.dropIndex("<index name>")
    

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 2019-01-05
      • 2020-05-11
      • 2023-03-25
      • 2021-07-25
      • 2021-10-01
      • 2019-09-10
      • 2022-07-26
      • 1970-01-01
      相关资源
      最近更新 更多