【问题标题】:How to insert multiple field data with same field name in database with mongoose, nodeJs ( Express )如何使用猫鼬,nodeJs(Express)在数据库中插入具有相同字段名称的多个字段数据
【发布时间】:2020-09-19 04:45:42
【问题描述】:

我是 nodejs 的新手,我正在尝试创建一个小项目来制作发票。 我想用 mongoose 和 express 将产品信息插入 mongodb,但我不知道该怎么做。

这是我的 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>

这是克隆产品文件的脚本...

<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>

这是 Express 中的路线..

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

当我提交表单时,控制台中只显示一个产品详细信息,例如..

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

但我需要这样...

    "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'
    },
}

你能指导我什么应该是 HTML 代码。

【问题讨论】:

  • 看起来您需要在这里查看多个内容。您的插入查询是什么样的?它有单个插入还是您使用的是 insertMany (docs.mongodb.com/manual/reference/method/…)。
  • 如果你最终在 api 中只使用了一个插入(如果你遵循严格的 CRUD),你是否从 ui 进行了多个 api 调用?你可能需要做两次。
  • @ronakvp 感谢对此发表评论....我将在单个插入中完成...您能告诉我是否应该更改输入属性名称,如产品 [],描述 [] 与我们用 PHP 做还是有其他方法?我需要上面提到的 req.body 数据。休息插入查询工作,我会尝试自己做。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

你需要将字段定义为数组,试试这个

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多