Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an array of objects in the request body

I am sending an array of objects to the server (as below), the server must receive the objects and add them to the mongodb. I'm new to node.js, I usually deal with the keys inside the rcevived request body (req.body). But here, the keys are the objects. How can I iterate over them?

[
    {
        id: "1",
        Name: "John"
    },
    {
        id: "2",
        Name: "Mark"
    },
    {   
        id: "3",
        Name: "Domi"
    }  
]

Server Code:

server.get('/user', function (req, res, next) {
//iterate over the objects in req.body
});

When I want to send one object I can easily get the the request content by req.body.id and req.body.Name, so how to do it with multiple objects inside the request body?

like image 446
zoma.saf Avatar asked Sep 29 '22 16:09

zoma.saf


1 Answers

something like this:

var bodyParser = require('body-parser');

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));

server.get('/user', function (req, res, next) {
   var data = req.body;

   data.forEach(function (item) {
       console.log(item.id);
       console.log(item.Name);
   });
}); 
like image 129
Arian Faurtosh Avatar answered Oct 03 '22 02:10

Arian Faurtosh