2017-10-07 15 views
0

私はAjaxを使用してフォーム内の複数のフィールドを追加(および削除)し、それらを保存するためにmongooseに送信します。 Unfortunatelly私は1つだけの配列を取り出して保存することができます。動的に追加された複数のファイルをmongooseに保存します

HTML:ここで私は名前を使って配列の属性inizialise目に見える形グループを使用してフォーム、と私はdinamicallyアヤックス

<form id="productAdd" class="form-horizontal" method="post" enctype="multipart/form-data" action="?_csrf={{csrfToken}}"> 
    <section class="panel"> 
    <div class="panel-body"> 
     <div class="form-group" data-option-index="1"> 
     <label class="col-md-3 control-label" for="optionType">Type</label> 
     <div class="col-md-1"> 
      <select class="form-control" name="options[0][optionType]"> 
      <option value="grams">Gr.</option> 
      </select> 
     </div> 
     <label class="col-md-1 control-label" for="value">Value</label> 
     <div class="col-md-1"> 
      <input type="text" class="form-control" name="options[0][optionValue]"> 
     </div> 
     <label class="col-md-1 control-label" for="price">Price</label> 
     <div class="col-md-1"> 
      <input type="text" class="form-control" name="options[0][optionPrice]"> 
     </div> 
     <div class="col-md-1"> 
      <button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button> 
     </div> 
     </div> 
     <div class="form-group hide" id="optionTemplate"> 
     <label class="col-md-3 control-label" for="optionType">Type</label> 
     <div class="col-md-1"> 
      <select class="form-control" name="optionType"> 
      <option value="grams">Gr.</option> 
      </select> 
     </div> 
     <label class="col-md-1 control-label" for="value">Value</label> 
     <div class="col-md-1"> 
      <input type="text" class="form-control" name="optionValue"> 
     </div> 
     <label class="col-md-1 control-label" for="price">Price</label> 
     <div class="col-md-1"> 
      <input type="text" class="form-control" name="optionPrice"> 
     </div> 
     <div class="col-md-1"> 
      <button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button> 
     </div> 
     </div> 
    </div> 
    <footer class="panel-footer"> 
     <div class="row"> 
     <div class="col-sm-9 col-sm-offset-3"> 
      <input type="hidden" name="_csrf" value="{{csrfToken}}"> 
      <button class="btn btn-primary">Submit</button> 
      <button type="reset" class="btn btn-default">Reset</button> 
     </div> 
     </div> 
    </footer> 
    </section> 
</form> 

AJAXを取り込むフォーム・グループのテンプレートがあります:私はこれを使用それぞれ3つの入力を持つ行を追加または削除します。私は.serializeを使用するフォームを送信する前に()その名前で

$(document).ready(function() { 
    var optionIndex = $(".form-group[data-option-index]").length; 
    $('#productAdd').submit(function(e) { // add product submit function 
    e.preventDefault(); 
    $(this).ajaxSubmit({ 
     contentType: 'application/json', 
     data: $('form[name="productAdd"]').serialize(), 
     error: function(xhr) { 
     console.log('Error: ' + xhr.status + ' ---- ' + xhr.responseText); 
     }, 
     success: function(response) { 
     if (typeof response.redirect === 'string') 
     window.location = response.redirect; 
     } 
    }); 
    return false; 
    }) 

    // Add button click handler 
    .on('click', '.addButton', function() { 
    optionIndex++; 
    var $template = $('#optionTemplate'), 
     $clone = $template 
     .clone() 
     .removeClass('hide') 
     .removeAttr('id') 
     .attr('data-option-index', optionIndex) 
     .insertBefore($template); 
    // Update the name attributes 
    $clone 
     .find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end() 
     .find('[name="optionValue"]').attr('name', 'options[' + optionIndex + '].optionValue').end() 
     .find('[name="optionPrice"]').attr('name', 'options[' + optionIndex + '].optionPrice').end(); 
    }) 
    // Remove button click handler 
    .on('click', '.removeButton', function() { 
    var $row = $(this).parents('.form-group'), 
    index = $row.attr('data-option-index'); 
    // Remove fields 
    $row.find('[name="options[' + index + '].title"]').remove(); 
    $row.find('[name="options[' + index + '].isbn"]').remove(); 
    $row.find('[name="options[' + index + '].price"]').remove(); 
    // Remove element containing the fields 
    $row.remove(); 
    }); 
}); 

NODEJSを配列を取得するには:ここに私のnodejsルートだ、私は、ファイルのアップロードを管理するためのmulterを使用しています。私はforeachがフォームから入力を管理する必要がありますが、最初の要素が表示されます。

router.post('/shop/products/add', [isLoggedIn, multer({dest: './public/images/products/'}).single('productPhoto')], function(req, res, next) { 
    var newProduct = new Product(); 
    newProduct.imagePath = req.file.filename; 
    newProduct.title = req.body.title; 
    newProduct.description = req.body.description; 
    newProduct.price = req.body.price; 
    newProduct.save() 
    .then(function (product) { 
     console.log(req.body.options); 
     req.body.options.forEach(function (option) { 
     var newOption = new ProductOption(); 
     newOption.type = option.optionType; 
     newOption.value = option.optionValue; 
     newOption.price = option.optionPrice; 
     newOption.product = product; 
     newOption.save(); 
     }); 
    }) 
    .then(function (options) { 
     req.flash('success', 'Product uploaded correctly.'); 
     res.send({redirect: '/user/shop/products/add'}); 
    }) 
    .catch(function (err) { 
     console.log('Error ' + err.code + ': ', err.message); 
     res.status(500).send('Failed to save the newAddress to DB: ' + err); 
    }); 
}); 

答えて

0

それは単純なミスだった、私はフィールドの名前dinamically異なり、静的なものから、追加。

.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end() 

この

.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '][optionType]').end() 
ようにする必要があり、このコード
関連する問題