{ 'id': req.body.groups.id, 'title': req.body.groups.title, 'teamMemberIds': [ req.body.groups.teamMemberIds] }]

You cannot access fields of array's elements like this: req.body.groups.id, req.body.groups.title and req.body.groups.teamMemberIDs. In order to get the fields in the nested array you would have to do something like this req.body.groups[index].id.

But doing all of that is not necessary, since your req.body and mongoose schema are the same you can simply pass in the whole req.body.groups into groups like shown below.

app.post(`/api/add`, async (req, res) => {
    collection.create( {  'id': req.body.id, 
                        'name': req.body.name, 
                        'date': req.body.date,
                        'groups': req.body.groups //change this line of code.
                    }, 
    (err, result ) => {
        if (err) {
            console.log('error', err)
        } else {
            console.log('updated', result);
            res.status(200).send(result);
        }
    })
});

Or even better you could just add the entire req.body to collection.create()

app.post(`/api/add`, async (req, res) => {
    collection.create(req.body, 
    (err, result ) => {
        if (err) {
            console.log('error', err)
        } else {
            console.log('updated', result);
            res.status(200).send(result);
        }
    })
});

In case when your req.body and mongoose schema have different formats, then for the array parts you can use the array method map to change the array format prior to document creation.

Answer from Sihoon Kim on Stack Overflow
🌐
Edureka Community
edureka.co › home › community › categories › blockchain › hyperledger fabric how to parse arrays in req...
Hyperledger Fabric How to Parse arrays in req body in node js express | Edureka Community
November 16, 2018 - I am getting an array in request body like this: [ { "month" : "JUL", "year" :"2018" } ... one. Can someone tell me how to pass both the parameters?
Discussions

Parsing arrays in req.body in node js express
If I pass two values in input , the 2nd value result overrides the first one . Any help on how can I get response for all the list of inputs with the overlapping part. Also , I need to sort the input values before calling the chaincode , like if I get Feb Mar Jan in the input , I should sort it as Jan Feb Mar and then run the for loop. Any help on this is appreciated. Thanks in advance. Thanks. ... Let's say you are receiving array in the post request ... More on stackoverflow.com
🌐 stackoverflow.com
How to send array as req.body on node js source?
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
April 1, 2016
How Can I Pass Array in http.request node?
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
May 9, 2014
node.js use request make http calls to transfer the correct array format array - Stack Overflow
json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON. ... Sign up to request clarification or add additional context in comments. More on stackoverflow.com
🌐 stackoverflow.com
September 5, 2017
🌐
Stack Overflow
stackoverflow.com › questions › 44343397 › passing-array-or-nested-objects-in-body-of-request-npm
node.js - Passing array or nested objects in body of request npm - Stack Overflow
June 3, 2017 - var js = JSON.parse(JSON.stringify(arr)); var blabla = {'item':'something',js} console.log(blabla); //-----> Object {item: "something", js: Array(2)} var js = JSON.parse(arr); var blabla = {'item':'something',js} console.log(blabla); //-----> ...
🌐
Stack Overflow
stackoverflow.com › questions › 36349288 › how-to-send-array-as-req-body-on-node-js-source
How to send array as req.body on node js source?
April 1, 2016 - In node.js, data_array = req.body.data; // now data_array is an array and can be indexed as data_array[0] and so on. Share · Improve this answer · Follow · answered Apr 1, 2016 at 7:27 · Himani Agrawal · 1,2721313 silver badges1414 bronze ...
🌐
Stack Overflow
stackoverflow.com › questions › 64125543 › send-array-in-fetch-body-node
node.js - Send array in fetch body Node - Stack Overflow
September 29, 2020 - const params = new URLSearchParams(); params.append("name", name); params.append("email", email); params.append("fields", fields); fetch(url, { headers: Authorization, method: "POST", body: params, }) .then((e) => { console.log(e); }) The request itself works fine, it's just fields that isn't picked up. ... Did you try something like. let fields = JSON.stringify([{ lastName: "test" }, { lastName: "test" }, { lastName: "test" }]) ? ... The param 'fields' has to be an array.
Find elsewhere
Top answer
1 of 2
9

Basically a comment on @udidu's good answer, but I want markdown formatting so I'll post it as an answer. Here's some minor improvement suggestions:

  • Omit everything but the path from the url "/deleteIds" on the javascript side so it will work no matter how it is served.

  • You can send the array as a JSON string without an object wrapper

    $.ajax({
        url: '/deleteIds',
        type: 'DELETE',
        data: JSON.stringify([1, 2, 3]),
        contentType: "application/json",
        processData: false,
        success: function(data){
            console.log(data);
        }
    });
    
  • In the server, the array will be available as just req.body

  • As per REST conventions, this should be using the HTTP DELETE method (I've changed the jquery. You will also need to change the express code to do app.del instead of app.post).

2 of 2
4

Ok, follow this instructions and you are good:

first of all, lets create our node server, I'm using the Express module to define the HTTP server:

var fs = require('fs'),
    express = require('express'),
    app = express();


app.listen(8080);

app.use(express.bodyParser());

app.get('/', function(req, res){
    var html = fs.readFileSync('index.html');
    res.header("Content-Type", "text/html");
    res.send(html);
});

app.post('/deleteIds', function(req, res){
    console.log(req.body.arr[0]);
    res.json({ success: true });
});

The server '/' request returns an HTML page that will create an jQuery Ajax request, Here is the HTML file content:

<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script type="text/javascript">

        $.ajax({
            url: 'http://localhost:8080/deleteIds',
            type: 'POST',
            data: {
                arr: [ 1, 2, 3]
            },
            success: function(data){
                console.log(data);
            }
        });

    </script>

</head>
<body>
</body>
</html>

As you can see, the Ajax request in the html file sent as a POST request with an array as the data, The /deleteIds express path POST function in the server listens to that and takes the array using req.body.arr, note that I'm using app.use(express.bodyParser());, without this line we will not be able to get the body content from the POST request.

This is it.. I hope this is helping understand Node + Ajax requests using express, from this point you can run on the arr and do what you want with the data.

🌐
Reddit
reddit.com › r/node › how to pass array via res.end to express?
r/node on Reddit: how to pass array via res.end to express?
December 28, 2021 -

I have an array and I want to receive it through a get request, but if I try to pass it

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Array

and if I turn the array into a string, then it will become a string (logical) and it will not work back into an array

🌐
Stack Overflow
stackoverflow.com › questions › 45994674 › how-to-send-array-post-get-parameter-with-node-js
How to send array POST/GET parameter with node.js
let params = { uri: getWsUrl(), body:queryString.stringify({ city: 885, customer: user.id, basket: [ [ product_id: 448025, count: 2 ] ] }) }; I use request.post(params, function(...)) method for send parameter to Webservice.
🌐
Stack Overflow
stackoverflow.com › questions › 58583646 › passing-array-from-js-to-nodejs
Passing array from js to Nodejs - javascript
October 28, 2019 - You can use "fetch" to send a post request to the backend. //frontend let nodesArray = [1,2,3]; let body = JSON.stringify({net:nodesArray}); fetch("/", {method:"post", body:body, headers: { 'Content-Type': 'application/json' }}); Your backend ...