gpt4 book ai didi

javascript - E11000重复键错误集合: Inserting document in mongodb

转载 作者:行者123 更新时间:2023-12-03 00:28:25 25 4
gpt4 key购买 nike

我正在为数据库做种以进行测试,因此我现在已在数据库中为每个我想插入 100 门类(class)的讲师插入了 15000 个讲师数据。所以我跑到for循环首先获取所有讲师 ID,其次为该讲师 ID 存储 100 个类(class),但在插入类(class)时出现此类错误

E11000 duplicate key error collection: Courser.courses index: ratings.user_1 dup key: { : null }

这是进入每位讲师的类(class)的代码

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)
}
}

我的类(class)模型定义看起来像这样

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;

最佳答案

在您的类(class)架构中,ratings 数组中的user 是一个唯一字段。在数据库中存储类(class)时,您没有给出任何独特的值(value)。第一次它会将值设置为空,但下次它会尝试为用户保存空值。因此违反了模式。删除 unique:true 或为用户传递唯一值

关于javascript - E11000重复键错误集合: Inserting document in mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com