我试图将数据插入myMongoDB数据库,我使用的是Referenced Documents,但我找不到任何方便的方法来插入数据(提取时非常方便)。
请在标记重复之前阅读它,我在发布之前搜索了整个Stackoverflow和github
这是我的考试模式
const ExamSchema = new mongoose.Schema({
name: {},
description: {},
allowedTime: {},
subject: {},
assignedInCharge: {},
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'MCQuestion' }]
});
以下是我的问题架构:
const MultipleChoiceQuestionSchema = new mongoose.Schema({
question: {},
answerOptions: [{}],
correctAnswer: {},
marksForCorrectAnswer: {},
negativeMark: {},
difficulty: {}
});
我的问题是:mongoose中是否有任何内置方法将数据放入我在文档中遗漏的数据库中(我已经在那里搜索了一千次)。
我的输入内容如下:
{
"name": "Sample Exam 1",
"description": "IDK if this will work",
"allowedTime": 123445666,
"subject": "testsub1",
"assignedInCharge": "someincharge",
"questions": [
{
"question": "this is que1",
"answerOptions": ["this is op 1", "this is op 2", "op 3", "op 4"],
"correctAnswer": "this is op 1",
"marksForCorrectAnswer": 4,
"negativeMark": 1,
"difficulty": 3
},
{}, {}, {}
]
}
并且(很遗憾长篇代码)我试图将数据插入数据库的目的是:
router.post('/admin/createExam', (request, response) => {
questions = request.body.questions;
var idarray = [];
questions.forEach(function(element) {
var question = new MCQuestion(element);
question.save().then((doc) => idarray.push(doc._id), (error) => console.log(error));
});
var body = _.pick(request.body, ['Everything Except Questions']);
body.questions = idarray;
var exam = new Exam(body);
exam.save().then(() =>{
response.send(exam);
}).catch((error) => {
response.status(400).send(error);
});
});
我能够将问题成功保存到问题集中,但考试合集未正确保存。
请帮助我,我已经在这上面扯了几个星期。
答案 0 :(得分:0)
没关系,我想通了,改变API方法使它变好了
router.post('/admin/createExam', (request, response) => {
var body = _.pick(request.body, ['name', 'description', 'allowedTime', 'subject', 'assignedInCharge']);
var exam = new Exam(body);
request.body.questions.forEach(function(element) {
element.exam = exam._id;
var question = new MCQuestion(element);
exam.questions.push(question._id);
question.save().catch((error) => console.log(error));
});
exam.save().then(() =>{
response.send(exam);
}).catch((error) => response.status(400).send(error));
});