Ryan Marren
Ryan Marren

Reputation: 31

MongoDB formatting error when posting JSON object using Node.js Express

I am making JSON objects that look like

var newSong = { 
        'name': 'Song',
        'genre': 'Genre',
        'percent': '100',
        'lyrics': [
                    {"line": "1", "lyric": "first lyric"}
         ]
   }

and then using Express and Node.js to update my MongoDB like this

//in global.js file
$.ajax({
        type: 'POST',
        data: newSong,
        url: '/songs/addsong',
        dataType: 'JSON'
    }).done(function( response ) {
        ...checking for errors...
        }
    });


//in songs.js (routes file)
router.post('/addsong', function(req, res) {
var db = req.db;
db.collection('daisy').insert(req.body, function(err, result){
    res.send(
        (err === null) ? { msg: '' } : { msg: err }
    );
});

and this works in posting something to my MongoDB.

However, what is posted looks like this:

{
    "_id" : ObjectId("54d6d8d12a5bed45055e6e1b"),
    "name" : "Song",
    "genre" : "Genre",
    "percent" : "100",
    "lyrics[0][line]" : "1",
    "lyrics[0][lyric]" : "first lyric"
}

Instead of how I need it to look:

{
    "_id" : ObjectId("54d6d8d12a5bed45055e6e1b"),
    "name" : "Song",
    "genre" : "Genre",
    "percent" : "100",
    "lyrics" : [
             {"line":1", "lyric": "first lyric"}
    ]
}

Let me know what on earth I am doing wrong!

Upvotes: 2

Views: 479

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

You need to JSON.stringify newSong so that it will be encoded as a JSON body. You also need to declare the right contentType so the service knows to interpret it as JSON.

$.ajax({
    type: 'POST',
    data: JSON.stringify(newSong),
    url: '/songs/addsong',
    contentType: 'application/json',
    dataType: 'JSON'
}).done(function( response ) {
    ...checking for errors...
});

Upvotes: 1

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

Use the following for your ajax call:

$.ajax({
        type: 'POST',
        data: newSong,
        url: '/songs/addsong',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    }).done(function( response ) {
        ...checking for errors...
        }
    });

Install the body-parser module if you haven't already:

npm install body-parser

Add the following lines in your code upon instantiating express

var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

Upvotes: 0

Related Questions