Parsing nested JSON using body-parser and express

andyopayne

I have an iOS app which is sending a JSON packet to a webserver. The webserver code looks like this:

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log("MongoDB connection is open.");
});

// Mongoose Schema definition
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
    X: Number,
    Y: Number,
    Orientation: Number,
    UserID: String,
    Time: String
});

// Mongoose Model definition
var LocationsCollection = mongoose.model('locations', LocationSchema);

// create application/json parser
var jsonParser = bodyParser.json();

// URL management
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.post('/update', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    else {
        console.log(req.body);
    }
});

// Start the server
var server = app.listen(3000, function () {
  var host = server.address().address
  var port = server.address().port
  console.log('App listening at %s:%s',host, port)
});

The key part is the app.post method which processes the incoming http request being sent from my iOS app. At the moment, the method which prints the req.body to the console looks like this:

{ 
  datapoint_1:
   { timestamp: '2015-02-06T13:02:40:361Z',
     x: 0.6164286615466197,
     y: -0.6234909703424794,
     id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
     orientation: 271.3345946652066 },
  datapoint_2:
   { timestamp: '2015-02-06T13:02:40:961Z',
     x: 0.6164286615466197,
     y: -0.6234909703424794,
     id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
     orientation: 273.6719055175781 }
}

So, you can see the request is a nested JSON object. Ideally, I'd like to loop through the request objects (ie. the datapoints) and insert those into the mongoDB database (via mongoose). However, I can't seem to figure out how to do much of anything with the req.body. I can't seem to create a loop to iterate through the request or how to properly parse the nested JSON file so it matches the mongoose schema. Can anyone provide some guidance on how to insert these datapoints into the mongoose database?

andyopayne

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.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Plug.Parser not reading/parsing JSON body

분류에서Dev

Parsing nested JSON using RetroFit for Android

분류에서Dev

body-parser json 포스트 데이터 읽기 node.js express

분류에서Dev

C# - How To Update Nested Values in JSON body using FormUrlEncodedContent?

분류에서Dev

express body-parser middleware puts data into the property name

분류에서Dev

Error while using body.json() for parsing response from http.get()

분류에서Dev

Express body-parser 요청이 표시되지 않음

분류에서Dev

Parsing JSON to Object using Jackson

분류에서Dev

Android Json Parsing Using GSON

분류에서Dev

body-parser bodyParser.json ()을 사용할 때 빈 json

분류에서Dev

simple htmldom parser not parsing microdata

분류에서Dev

android parsing json data using ION

분류에서Dev

Parsing JSON with @

분류에서Dev

What parsing strategy is used on Stanford Parser?

분류에서Dev

JSON parser tip in C

분류에서Dev

Using stringify for nested JSON to use in localStorage

분류에서Dev

Parsing base64 using JSON file in Java

분류에서Dev

How to pass JSON body using node to call REST service?

분류에서Dev

Using `err` in a Child Parser

분류에서Dev

Using `err` in a Child Parser

분류에서Dev

Express req.body is in quotes

분류에서Dev

Get the elements from nested JSON with Python using json lib

분류에서Dev

Express 4 Multer / req.body 및 res.json이 정의되지 않았습니다.

분류에서Dev

Express 4 Multer / req.body 및 res.json이 정의되지 않았습니다.

분류에서Dev

node.js v0.12.7, express 4, body-parser, bootstrap 3을 사용하여 POST 데이터를 검색 할 수 없습니다.

분류에서Dev

C# JSON & Parsing

분류에서Dev

Parsing twitter json response

분류에서Dev

Parsing a json file in JAVA

분류에서Dev

Java JSON Simple Parsing

Related 관련 기사

뜨겁다태그

보관