Jake 1986
Jake 1986

Reputation: 602

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

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.

Upvotes: 0

Views: 425

Answers (1)

Sam Ballan
Sam Ballan

Reputation: 26

If I understand, @jake1986 doesn't want a separate property on req.body for each question; he wants it in a single data structure.

If that's the case, I would probably write a function for the front end to assemble question objects with properties like the mongo entry you described, and out them all into an array. The array would be sent in a POST request. You can add these as documents to Mongo by passing this array to the create() function.

Upvotes: 1

Related Questions