【问题标题】:How to store user input into MongoDB without specific req.body?如何在没有特定 req.body 的情况下将用户输入存储到 MongoDB?
【发布时间】:2016-07-11 22:09:01
【问题描述】:

我正在尝试允许我网站的用户创建他们自己的测验,但我在如何最好地将他们的测验导入 MongoDB 时遇到了问题。

一个问题是用户提交的测验可以有任意数量的问题,所以我认为具体引用每个问题并使用 req.body 回答是没有意义的。这意味着给每个问题和答案一个唯一的名称属性,如下所示:

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">

用户可以通过单击“新问题”按钮添加更多问题,因此测验可能会很长。

最终我希望用户创建的测验以如下格式存储在 MongoDB 中:

[{
  "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
}]

提前感谢您的任何指导。

【问题讨论】:

  • 不确定如何假装在没有POST请求正文的情况下将数据发送到服务器。用户输入的数据必须以某种方式到达服务器,为什么不使用req.body?澄清这个问题后,我可以帮助您进行数据建模。
  • 您无需在请求中单独发送每个答案和问题。您可以在发布到服务器之前创建一个包含问题及其答案的对象数组,将该数组字符串化,并将其作为一个字段传递到 req.body
  • @DavidEspino 澄清一下,我在制作大量 req.body 时遇到了问题,但现在看起来最好的方法是在前端编译所有值,然后使用一个 req.body 将该数据结构带到 MongoDB。谢谢!

标签: node.js forms mongodb express


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多