【发布时间】:2016-06-24 19:43:52
【问题描述】:
这是一个 node.js、Express 和 Mongoose 项目。
我正在尝试将表单字段(水果的价格)中的输入推送到数组中。我的数据库中有水果的名称。每一块水果可以有很多价格。用户在我的表单中以数组的形式输入水果的许多不同价格。
router.post('/fruit', function(req, res) {
//Some code to match the name of the fruit entered by user to the name of the fruit in the DB
if(!existingFruit) {
//Some code
}
if(existingFruit) {
Fruit.findOneAndUpdate({fruit: req.body.fruit}, {
$push: { price: req.body.price1 }},
//Some code which tells the user whether the price they entered was inserted into the DB or not
});
这是有问题的输入字段:
<label for="price1">Price</label>
<input type="text" name="price1" id="price1"/>
<label for="price2">Price</label>
<input type="text" name="price2" id="price2"/>
作为我的后端代码和表单字段,只有在“price1”中输入的价格才会被插入到数据库中。
所以我想知道...有没有办法让我一遍又一遍地循环我的后端代码,以检索输入字段“price2”、“price3”等中输入的值...
【问题讨论】:
-
也许:..{ 价格:[req.body.price1, req.body.price2,...]}...?
-
这个问题是用户可以输入从 1 到无限的价格(他们可以访问一个 +/- 按钮,让他们添加价格字段)。所以你建议的方法在这种情况下是行不通的。
-
它适用于更新 Mongo 集合字段的部分,因为它应该是一个数组。要了解如何处理任意数量的值,请查看 Paul amd PRDeving 的答案。
标签: javascript node.js