我正在开发一个基于React(前端)和Node js(后端为 mongodb )的应用程序。在同事处理后端时,我主要是在前端上工作。该应用程序的数据库结构如下:
当我在数据库中添加问题时,我提供了一个选项列表,其中一个是答案。在后端,问题存储在单独的文档中,而答案存储在单独的文档中;持有问题的ID作为参考。问题文档的外观为。另一方面,答案文档的结构为。如您所见,每个答案对象都持有对其各自问题的引用。如果我发出HTTP GET请求以获取问题列表,它将返回带有空答案数组的问题对象。但是,这不是所需的行为。后端代码段如下:
const _ = require('lodash');
const {Question, validate} = require('../models/questions');
const {Answer} = require('../models/answers');
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
router.get('/', async (req, res) => {
const questions = await Question.find({ isDeleted: false }).sort('dateCreated');
res.send(questions);
});
router.post('/', async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let question = new Question(_.pick(req.body, ['questionText', 'sectionId']));
//save data in collection
await question.save();
let ans_Obj= req.body.answer;
Object.keys(ans_Obj).map( async function(key) {
let answer = new Answer({
ans_text: ans_Obj[key].answer,
questionId: question._id,
isCorrect: ans_Obj[key].isCorrect
});
/// save answers for given question ID
await answer.save();
});
res.send(question);
});
router.put('/:id', async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const question = await Question.findByIdAndUpdate(req.params.id,
{
questionText: req.body.questionText,
sectionId: req.body.sectionId,
dateModified: new Date()
}, {
new: true
});
/// need to update ans as well, if admin removes or updates any ans.
///left it for future implementation
if (!question) return res.status(404).send('The question with the given ID was not found.');
res.send(question);
});
router.delete('/:id', async (req, res) => {
const question = await Question.findByIdAndUpdate(req.params.id,
{
isDeleted:true
},{
new:true
});
if (!question) return res.status(404).send('The question with the given ID was not found..');
res.send(question);
});
router.get('/:id', async (req, res) => {
const question = await Question.findById(req.params.id);
if (!question) return res.status(404).send('The question with the given ID was not found.');
res.send(question);
});
module.exports = router;
如您所见,在router.GET
部分中,仅会提取问题,因为它会返回空答案数组。
我的问题是:如何从ANSWERS文档中检索答案并将答案插入各自的问题中?如有任何帮助或建议,请先感谢。