我正在尝试使用 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);