无法将默认值添加到数组中的对象



我正在尝试将花哨的项目添加到下面的模型中。每当我尝试添加下一个花哨的ITem时,我都会得到mongo db错误:

MongoError: E11000 重复键错误集合: natours.fancyitems 索引: books.name_1 dup 键: { : null }

为了避免这种情况,我正在尝试将默认值添加到对象中,以免出现此重复错误。

请提出更好的方法来处理这个问题!

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;

您提供的错误表明已经有一条以 null 作为名称的记录。换句话说,你已经有一本没有名字的书了。

相关文档:

如果文档在唯一 索引,索引将存储此文档的空值。以 唯一的约束,MongoDB将只允许一个文档 缺少索引字段。如果有多个文档没有 索引字段的值或缺少索引字段,索引 生成将失败,并出现重复键错误。

您可以将唯一约束与稀疏索引结合使用以进行筛选 这些空值来自唯一索引并避免错误。

唯一索引

稀疏索引仅包含具有 索引字段,即使索引字段包含 null 值。

稀疏索引

最新更新