【问题标题】:html form submits arrays in one cellhtml 表单在一个单元格中提交数组
【发布时间】:2019-06-08 05:02:48
【问题描述】:

在我的 html 表单中,我想在不同的单元格中添加数组,但它会将所有内容都推送到一个单元格中。

这是我的 html 输入:

<input class="recinputs" type="text" name="ingredients[ingredient]" value="egg">
<input class="recinputs" type="text" name="ingredients[amount]" value="2">
<input class="recinputs" type="text" name="ingredients[ingredient]" value="salt">
<input class="recinputs" type="text" name="ingredients[amount]" value="200 gr">

这是我的猫鼬模式:

  ingredients: [{
    ingredient: {
      type: String,
      ref: 'Ingredient'
    },
    amount: {
      type: String,
    }
  }]

身体看起来像这样:

   { ingredient: [ 'egg', 'salt' ],
     amount: [ '2', '200 gr' ] },

并将数据保存在一个单元格中。 但我希望它在不同的单元格中添加每一个。 我应该如何更改我的输入?

提前致谢!

【问题讨论】:

    标签: html arrays forms express mongoose


    【解决方案1】:

    我真的不知道是什么所以命名约定可能有点混乱..但它给出了你想要的尝试使用这段代码

    let objArray = [];
    let foodItem = {ingredient: null, amount : null}
    
    for(let i = 0; i< obj.ingredient.length ;i++){
        foodItem.ingredient = obj.ingredient[i];
        foodItem.amount = obj.amount[i];
        objArray.push(foodItem);
        foodItem = {ingredient: null, amount : null};
    }
    

    所以使用你的模型你应该这样做

    let item = new Model(objArray ); 
    

    objArray 是这样创建的

    0: {ingredient: "egg", amount: "2"}
    1: {ingredient: "salt", amount: "200 gr"}
    

    然后最后使用 item.save();

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2015-02-14
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多