【发布时间】:2018-12-31 04:18:44
【问题描述】:
我正在为我的数据库播种以进行测试,因此我现在已在数据库中插入了 15000 条讲师数据,以供我要插入 100 门课程的每位讲师使用。所以我跑到for循环 首先获取所有讲师 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;
【问题讨论】:
标签: javascript node.js mongodb mongoose mongodb-query