6

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?

zoma.saf
  • 558
  • 3
  • 6
  • 14

1 Answers1

4

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);
   });
}); 
Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115