【问题标题】:Loop a function in node.js在 node.js 中循环一个函数
【发布时间】: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


【解决方案1】:

您可以这样做来迭代所有字段:

let i = 0;
let field;
while (field = form['price' + i++]) {
   ...
}

【讨论】:

  • 我假设你的意思是我将它添加到我的后端代码中?一些问题......第一个是我当前版本的节点不允许使用'let'。第二个问题是我不太确定如何将您的代码添加到我的代码中? “字段”到底应该代表什么?我知道,我在这方面很糟糕。
【解决方案2】:

Express body-parser 在表单的字段名称中使用数组访问约定。因此,如果您将表单输入命名为:prices[0],那么当正文到达您的 post 方法时,它将成为 req.body.prices 中的第一个元素。

Fwiw 你也可以做对象,所以如果你想要一个包含名称和值的水果数组,你可以创建名称为“fruits[0].name”和“fruits[0].prices[0]”的表单输入

【讨论】:

  • 因此将我的价格字段名称更改为:price[0] 和 price[1]。但是我如何调整我的后端代码的这一部分以使其工作:req.body.price
  • 现在将是一个数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
  • 2019-10-18
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
相关资源
最近更新 更多