gpt4 book ai didi

node.js - 在引用文档中插入数据?

转载 作者:太空宇宙 更新时间:2023-11-04 01:59:56 25 4
gpt4 key购买 nike

我正在尝试将数据插入到 myMongoDB 数据库中,我正在使用引用文档,但我找不到任何方便的方法来插入数据(虽然获取非常方便)。
请在标记重复之前阅读它,我在发布之前搜索了整个 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);
});

});

我能够成功将问题保存到问题集合中,但考试集合未正确保存。

The Questions collection

The Exam Collection

请帮助我,我已经为此烦恼了好几个星期了。

最佳答案

没关系,我想通了,改变 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));

});

关于node.js - 在引用文档中插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46387926/

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