简体   繁体   中英

How to insert multiple field data with same field name in database with mongoose, nodeJs ( Express )

I am new to nodejs and I am trying to create a small project for making invoice. I want to insert products information into mongodb with mongoose and express but i have no idea how to do it.

This is my HTML Code...

    <form action="/" method="POST">
    <div>
        <input type="text" name="product_name" />
        <input type="text" name="description" />
        <input type="number" name="quantity" />
        <input type="number" name="price" />
        <input type="number" name="discount" />
        <input type="number" name="total" />
    </div>
    <div id="product"></div>
</form>

This is Script to clone product fileds...

<script>
  var addProduct = ()=>{
  var content = document.createElement("div");
  content.innerHTML = `<input type="text" name="product_name" />
    <input type="text" name="description" />
    <input type="number" name="quantity" />
    <input type="number" name="price" />
    <input type="number" name="discount" />
    <input type="number" name="total" />`;
  document.getElementById("product").appendChild(content);
  }
</script>

This is route in Express..

router.post('/', (req, res)=> { 
console.log(req.body); 
res.redirect('/'); 
})

When I submit the form, only one product detail is showing in console like..

    {
      product_name: 'Shop',
      description: 'Cinthol',
      quantity: '1',
      price: '30',
      discount: '5',
      total: '25',
}

But i need it like this...

    "products": {
    "1": {
        "product_name": 'Shop',
        "description": 'Cinthol',
        "quantity": '1',
        "price": '30',
        "discount": '5',
        "total": '25'
    },
    "2": {
        "product_name": 'Shop',
        "description": 'Dettol',
        "quantity": '1',
        "price": '35',
        "discount": '2',
        "total": '33'
    },
}

so can you please guide me what should be the HTML code.

You need to define fields as array,Try This

<pre>
<form>
<input type="text" name="product_name[]" />
    <input type="text" name="description[]" />
    <input type="number" name="quantity[]" />
    <input type="number" name="price[]" />
    <input type="number" name="discount[]" />
    <input type="number" name="total[]" />
</form>
</pre>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM