【发布时间】:2018-03-05 09:40:30
【问题描述】:
我正在尝试将数据插入到我的 MongoDB 数据库中,我正在使用引用文档,但我找不到任何方便的方法来插入数据(虽然提取非常方便)。
请在标记重复之前阅读它,我在发布之前搜索了整个 Stackoverflow 和 github
这是我的考试架构
const ExamSchema = new mongoose.Schema({
name: {},
description: {},
allowedTime: {},
subject: {},
assignedInCharge: {},
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'MCQuestion' }]
});
And Follows 是我的问题架构:
const MultipleChoiceQuestionSchema = new mongoose.Schema({
question: {},
answerOptions: [{}],
correctAnswer: {},
marksForCorrectAnswer: {},
negativeMark: {},
difficulty: {}
});
我的问题是:猫鼬中是否有任何内置方法可以将数据放入我在文档中丢失的数据库中(我已经在那里搜索了一千次)。
我的输入如下:
{
"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
},
{}, {}, {}
]
}
并且(对不起,长 sn-ps)我试图将数据插入数据库的操作是:
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);
});
});
我能够成功地将问题保存到问题集合中,但未正确保存考试集合。
请帮助我,我已经为此烦恼了好几个星期了。
【问题讨论】:
标签: node.js mongodb mongoose mongoose-populate