我正在播种数据库以进行测试,所以现在我要为每个要插入100门课程的讲师插入15000个讲师数据。所以我跑了循环 首先获取所有教师ID,其次为该教师ID存储100门课程,但是在插入课程时出现这种错误
E11000 duplicate key error collection: Courser.courses index: ratings.user_1 dup key: { : null }
这是每个教师进入课程的代码
seedCourse: async (req, res, next) => {
try {
const instructors = await Instructor.find();
//const insrtuctor contains 15000 instructor
for(let oneInst of instructors) {
for(let i=0; i<=100; i++) {
const course = await new Course({
title: faker.lorem.sentence(),
description: faker.lorem.paragraph(),
author: oneInst._id,
prise: Math.floor(Math.random()*6 + 4),
isPublished: 'true',
tags: ["java", "Nodejs", "javascript"]
});
const result = await course.save();
await Instructor.findByIdAndUpdate(oneInst._id, { $push: { courses: result._id } });
console.log(`Instructor Id ${oneInst._id} Course added ${i}`);
}
}
} catch (error) {
next(error)
}
}
我的课程模型定义看起来像这样
const mongoose = require('mongoose');
const Course = mongoose.model('courses', new mongoose.Schema({
title: {
type: String,
required: true,
minlength: 3
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'instructor'
},
description: {
type: String,
required: true,
minlength: 5
},
ratings: [{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
required: true,
unique: true
},
rating: {
type: Number,
required: true,
min: 0,
max: 5
},
description: {
type: String,
required: true,
minlength: 5
}
}],
tags: [String],
rating: {
type: Number,
min: 0,
default: 0
},
ratedBy: {
type: Number,
min: 0,
default: 0
},
prise: {
type: Number,
required: function() { this.isPublished },
min: 0
},
isPublished: {
type: Boolean,
default: false
}
}));
module.exports = Course;
答案 0 :(得分:1)
在user
数组中的课程模式ratings
中,是一个唯一字段。在DB中存储课程时,您没有给出任何唯一的值。第一次将工具值设置为null,但是下次尝试为用户保存null值。因此违反了架构。
删除unique:true
或为用户传递唯一值