How to store user input into MongoDB without specific req.body?

时间:2016-07-11 22:09:02

标签: node.js forms mongodb express

I am trying to allow users of my site to create their own quizzes, but I am having a problem with how to best get their quizzes into MongoDB.

One issue is that the quiz the user submits can have any number of questions, so I don't think it makes sense to specifically reference each question and answer with req.body. Which would mean giving each question and answer a unique name attribute, like below:

Question:<input type="text" name="question1">
<br>answer:<input type="text" name="ans1a">
<br>answer:<input type="text" name="ans1b">
<br>answer:<input type="text" name="ans1c">

Question:<input type="text" id="question2">
<br>answer:<input type="text" name="ans2a">
<br>answer:<input type="text" name="ans2b">
<br>answer:<input type="text" name="ans2c">

The user can add more questions by clicking a 'new question' button, so the quiz could be very long.

Ultimately I want the user's created quizzes to be stored in MongoDB in a format something like this:

[{
  "question": "Which of these involves the analysis of of a business's financial statements, often used in stock valuation?",
  "choices": ["Fundamental analysis", "Technical analysis"],
  "correct": 0
}, {
  "question": "What was the name of the bond purchasing program started by the U.S. Federal Reserve in response to the 2008 financial crisis?",
  "choices": ["Stimulus Package", "Mercantilism", "Quantitative Easing"],
  "correct": 2
}, {
  "question": "Which term describes a debt security issued by a government, company, or other entity?",
  "choices": ["Bond", "Stock", "Mutual fund"],
  "correct": 0
}]

Thanks in advance for any guidance.

1 个答案:

答案 0 :(得分:1)

如果我理解,@ jake1986不希望每个问题在req.body上有单独的属性;他希望它在一个单一的数据结构中。

如果是这种情况,我可能会为前端编写一个函数来组合问题对象,其中包含您描述的mongo条目等属性,并将它们全部放入数组中。该阵列将在POST请求中发送。您可以通过将此数组传递给create()函数将这些文档作为文档添加到Mongo。