Reputation: 127
I am trying to add the fancyItem to the below model. Whenever I try to add the next fancyITem I get below mongo db error:
MongoError: E11000 duplicate key error collection: natours.fancyitems index: books.name_1 dup key: { : null }\n
To avoid this I am trying to add the default values to the objects so that I don't get this duplicate error.
Kindly suggest better way to handle this issue!
const mongoose = require("mongoose");
const fancyItemSchema = new mongoose.Schema({
firstName: {
type: String,
required: [true, "Please enter fancyItem's first name"]
},
lastName: {
type: String
},
genre: {
type: String,
enum: [
"guidingLights",
"luminaries",
"mavericScientists",
"menOfLetters",
"theGrandPhilosophers",
"architectsOfTheFuture"
],
required: true
},
notableWork: {
type: String,
required: [true, "Please enter notable work"]
},
quotes: [
{
quote: {
type: String,
default: "There is no quote"
}
}
],
books: [
{
bookName: {
type: String,
sparse: true,
default: "There is no quote"
},
bookURL: {
type: String,
sparse: true,
default: "There is no quote"
}
}
],
videos: [
{
videoName: {
type: String,
maxlength: [
50,
"A video description must have less or equal to 50 characters"
],
sparse: true,
default: "There is no quote"
},
videoURL: {
type: String,
sparse: true,
default: "There is no quote"
}
}
],
courses: [
{
courseName: {
type: String,
sparse: true,
default: "There is no quote"
},
courseURL: {
type: String,
sparse: true,
default: "There is no quote"
},
platform: {
type: String,
sparse: true,
default: "There is no quote"
}
}
]
});
const FancyItem = mongoose.model("FancyItem", fancyItemSchema);
module.exports = FancyItem;
Upvotes: 0
Views: 65
Reputation: 516
Error you have provided says that there's already a record with null as the name. In other words, you already have a book without a name.
The relevant documentation for this:
If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.
You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.
Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.
Upvotes: 3