简体   繁体   English

如何使用mongoose,nodeJs(Express)在数据库中插入具有相同字段名称的多个字段数据

[英]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.我是 nodejs 的新手,我正在尝试创建一个用于制作发票的小项目。 I want to insert products information into mongodb with mongoose and express but i have no idea how to do it.我想用猫鼬和快递将产品信息插入到 mongodb 中,但我不知道该怎么做。

This is my HTML Code...这是我的 HTML 代码...

    <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.所以你能指导我什么应该是 HTML 代码。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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