【问题标题】:E11000 duplicate key error collection: Inserting document in mongodbE11000 重复键错误收集:在 mongodb 中插入文档
【发布时间】: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


    【解决方案1】:

    在您的课程架构中,user 中的 ratings 数组是一个唯一字段。在数据库中存储课程时,您没有提供任何独特的价值。第一次它的工具值为空,但下一次它试图为用户保存空值。因此违反了模式。 删除unique:true 或为用户传递一个唯一值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-04
      • 2022-08-16
      • 1970-01-01
      • 2017-02-20
      • 2020-12-08
      • 1970-01-01
      • 2019-04-01
      • 2018-10-12
      相关资源
      最近更新 更多