简体   繁体   English

如何使用express.js和mongoclient将数组插入mongodb

[英]How to insert an array to mongodb using express.js and just mongoclient

I'm learning mean stack and just wanted to try insert data into myphonebook db using just the mongoclient, i don't want to use mongoose for now. 我正在学习平均堆栈,只是想尝试仅使用mongoclient将数据插入到myphonebook db中,我现在不想使用mongoose。

How do i insert an array of objects into mongodb? 如何将对象数组插入mongodb? let's say more than 1 address and mobile numbers. 假设有多个地址和手机号码。 I'm not sure how to use the req.body.address or req.body.number 我不确定如何使用req.body.address或req.body.number

here's my code inside the mongoclient: 这是我在mongoclient中的代码:

router.post('/', (req,res)=>{

        var newEntry = {
            firstname: req.body.firstname,
            lastname: req.body.lastname,
            address:[
                // what's the right code here?
            ],
            mobile_numbers:[
                // what's the right code here
            ]
        }

        db.collection("data").insert(newEntry);
        res.redirect('/');

    }); 

and here's the key and value pairs i want to go inside the ff: 这是我想进入ff的键和值对:

  1. just string for the address 只是字符串作为地址
  2. mobile_numbers array: mobile_numbers数组:

    {"number": "1234567", "subscriber": "test"} {“数字”:“ 1234567”,“订户”:“测试”}

i'm using a basic form. 我正在使用基本表格。

<form action="/" method="POST">
    <input type="text" name="firstname" placeholder="Enter firstname">
    <input type="text" name="lastname" placeholder="Enter lastname">
    <input type="text" name="address" placeholder="Enter address">
    <input type="text" name="mobileno" placeholder="Enter mobile no.">
    <input type="text" name="subscriber" placeholder="Enter mobile no.">
    <input type="submit" value="Submit">
</form>

This will completely depend on how you structure the HTML form and in what structure/format you are sending it to the node js API. 这将完全取决于您如何构造HTML表单以及将其发送到节点js API的结构/格式。

If you are sending them in separate fields, you could directly add them in the query in the following way: 如果要在单独的字段中发送它们,则可以通过以下方式将它们直接添加到查询中:

    mobile_numbers:[
         {number:req.body.num1,subscriber:req.body.sub1},
         {number:req.body.num2,subscriber:req.body.sub2}
    ]

Or if you are sending the data in an array, then you could use a forEach and then create the desired structure and then attach it to the query. 或者,如果要以数组形式发送数据,则可以使用forEach然后创建所需的结构,然后将其附加到查询中。

Or you could just send the data in the desired structure from the UI itself and the just attach the object to the query 或者,您可以只从UI本身以所需的结构发送数据,然后将对象附加到查询中

    mobile_numbers: req.body.mobile_numbers

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

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