Parsing nested JSON using body-parser and express
Set body-parser's extended
property to true
to allow parsing nested objects.
var express = require('express');var app = express()var bodyParser = require('body-parser');app.use(bodyParser.urlencoded({ extended: true}));
Answering my own question. But, after figuring out how to access the key/value pairs inside the nested JSON object... it became relatively easy to figure out the rest. The updated app.post function now looks like this:
app.post('/update', jsonParser, function (req, res) { if (!req.body) return res.sendStatus(400); else { for(var datapoint in req.body){ //create new instance of LocationCollection document var point = new LocationsCollection({ X:Number(req.body[datapoint]["x"]), Y:Number(req.body[datapoint]["y"]), Orientation:Number(req.body[datapoint]["orientation"]), Time:req.body[datapoint]["timestamp"], UserID:req.body[datapoint]["id"] }); //insert the newly constructed document into the database point.save(function(err, point){ if(err) return console.error(err); else console.dir(point); }); } }});
I can test if this worked by putting the following method inside the callback function once the mongodb connection is first established:
//Find all location points and print to the console.console.log("Searching for all documents in Location Points Collection");LocationsCollection.find(function(err,data){ if(err) console.error(err); else console.dir(data);});
This will print any documents that have been previously added to the database. Hopefully this helps.
Try somthing like this.
var app = express();var bodyParser = require('body-parser');app.use(bodyParser.json({limit:1024*1024, verify: function(req, res, buf){ try { JSON.parse(buf); } catch(e) { res.send({ error: 'BROKEN_JSON' }); }}}));