2015-02-08 60 views
2

我在做,看起來像MongoDB的格式錯誤時發佈使用Node.js的快速

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

JSON對象,然後使用Express和Node.js的更新我的MongoDB這樣的

//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 } 
    ); 
}); 
JSON對象

,這個工作發佈到我的MongoDB。

但是,什麼是公佈如下:

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

而不是我怎麼需要它來看看:

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

讓我知道究竟我做錯了!

回答

0

使用你的Ajax調用以下:

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

安裝體解析器模塊,如果您尚未:

npm install body-parser 

在具現化表達

添加在你的下面幾行代碼
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()) 
+0

我已經在我的代碼中包含了所有這些。重新安裝body-parser和一切都無濟於事。 – 2015-02-08 04:31:50

1

您需要JSON.stringifynewSong以便它將被編碼爲JSON主體。您還需要聲明正確的contentType,以便服務知道將其解釋爲JSON。

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

我正在參加黑客馬拉松賽,並一直要求高科技公司,genuis學生和教授的工程師在這裏工作2個小時。然後你用2個神奇的代碼行來修復每一個問題!你是一個真正的神。非常感謝你 – 2015-02-08 05:03:20