2015-02-08 63 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