MongoError: E11000 重复键错误集合:myFirstDatabase.tours index: rating_1 dup key: { rating: null }
当我使用 postman 创建数据时,我不明白这个错误,说 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"]
}
答案 0 :(得分:0)
您在该集合中拥有唯一的评分索引。由于您在添加时未指定评分,因此评分为空,因此您在第一个之后出现此错误。 由于您尝试添加的后续数据也没有评级,因此它们的评级为空,与索引冲突。
首先,前往您的 mongo 控制台。
运行此命令
db.<collection>.getIndexes()
你应该有这样的记录
{
"v" : 2,
"unique" : true,
"key" : {
"rating" : 1
},
"name" : "rating"
}
接下来,运行此命令删除索引
db.<collection>.dropIndex("<index name>")