【发布时间】:2018-12-12 12:11:51
【问题描述】:
我在 MongoDB 中从用户表单构建数据时遇到问题。
我理想的文档结构是这样的:
如您所见,成分位于可迭代的数组中。
但是,在提交表单时,我无法找到方法来执行此操作。我的成分部分的表格如下所示:
<h4>Ingredients</h4>
</div>
<div class="row">
<div class="input-field col s6">
<input id="ingredients_1_name" name="ingredients_name_1" type="text" class="validate" required>
<label for="ingredients_1_name">Ingredient</label>
</div>
<div class="input-field col s3">
<input id="ingredients_1_quantity" name="ingredients_quantity_1" type="text" class="validate" required>
<label for="ingredients_1_quantity">Quantity</label>
</div>
<div class="input-field col s3">
<input id="ingredients_1_unit" name="ingredients_unit_1" type="text" class="validate" required>
<label for="ingredients_1_unit">Unit</label>
</div>
</div>
用户可以按下一个 JavaScript 按钮,添加一个名为“ingredients_2_name”的新行,依此类推。这导致了一个非常非结构化的数据库:
这显然是一团糟,在使用数据时需要进行不必要的操作。
我似乎在网上找不到任何关于如何以定义的方式将数据从 HTML 表单发送到 MongoDB 的信息。
目前在提交表单时,视图如下:
@app.route('/insert_recipe/', methods=['GET','POST'])
def insert_recipe():
"""
This function is called when a user clicks the submit button on the add
recipe form. Uses the insert_one() method to add to the recipes document.
"""
recipes = mongo.db.recipes
dictionary = recipes.insert_one(request.form.to_dict())
return redirect(url_for("get_recipes"))
这只是将输入名称作为键,将用户输入作为值。
是否有人能够描述我如何以结构化的方式在 MongoDB 中存储表单数据?
【问题讨论】:
标签: python html mongodb flask pymongo