使用Node / Express / Mongoose保存到MongoDB

时间:2015-07-22 20:22:05

标签: node.js mongodb express mongoose body-parser

我正在尝试保存新的"播放列表"使用node / express / bodyParser / mongoose的组合到mongoDB。这是我到目前为止的代码:

router.route('/playlists')

// create a playlist (accessed at POST http://localhost:8080/api/playlists)
.post(function(req, res) {

    var playlist = new Playlist({});      // create a new instance of the Playlist model
    playlist.businessName = req.body.businessName;
    playlist.businessEmail = req.body.businessEmail;

    // save the playlist and check for errors
    playlist.save(function(err) {
        if (err)
            res.send(err);

        res.json({ message: playlist.businessName + " created a playlist with email - " + playlist.businessEmail + " - " + playlist });
    });

});

当我使用POSTMAN发布时,我得到以下回复:

"message": "Test Business created a playlist with email - test@gmail.com - { __v: 0, _id: 55aff6c368f7d3ac2f000001 }"

playlist.businessName和playlist.businessEmail都像我预期的那样返回,但是这些没有显示在数据库中或仅显示在播放列表响应中。发布时,只有以下内容显示在数据库中:

{     " _id":{         " $ oid":" 55aff680551ec57031000001"     },     " __ v":0 }

然而,当我删除其中一个键:值对并改变它时,它会起作用:

router.route('/playlists')

// create a playlist (accessed at POST http://localhost:8080/api/playlists)
.post(function(req, res) {

    var playlist = new Playlist({});      // create a new instance of the Playlist model
    playlist.name = req.body.businessName;
    //playlist.businessEmail = req.body.businessEmail;

    // save the playlist and check for errors
    playlist.save(function(err) {
        if (err)
            res.send(err);

        res.json({ message: playlist.name + " created a playlist - " + playlist });
    });

});

数据库/文档中的数据:

{
"_id": {
    "$oid": "55aff94e214389d83c000001"
},
"name": "Test Business",
"__v": 0

}

playlist.name现在显示在文档中。我的问题是如何将playlist.name和playlist.email等保存到文档中?

更新

更新架构后,所有内容现在都按预期工作。

旧架构:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var PlaylistSchema   = new Schema({
    name: String
});

module.exports = mongoose.model('Playlist', PlaylistSchema);

更新了架构:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var PlaylistSchema   = new Schema({
    businessName: String,
    businessEmail: String
});

module.exports = mongoose.model('Playlist', PlaylistSchema);

0 个答案:

没有答案