当我从Postman执行此功能时:
router.get('/db', function(req, res, next) {
tune.find({}, function (err, results) {
res.json(results);
});
});
我的数据库返回:
[{"_id":"56f30425ba97bb301fe6ab1a","__v":0},
{"_id":"56f30514f9b7ea3b1f1fd9f7","__v":0},
{"_id":"56f306bb9c8203451f2cc58a","__v":0},
{"_id":"56f306ca9c8203451f2cc58b","__v":0},
{"_id":"56f306e99c8203451f2cc58c","__v":0},
{"_id":"56f33d43b64d540b208b6c3c","__v":0}]
我的猫鼬模式:
var Schema = mongoose.Schema;
var track = new Schema({
title: String,
artist: String,
genre: String
});
var tune = mongoose.model('tune', track);
我的帖子:
router.post('/db', function(req, res, next) {
var tune1 = new tune(req.body);
tune1.save(function (err) {
if (err) { console.log('error!');}
else {
res.json({message: 'Track successfully posted'});
}
});
});
请求发布:
app.use('/users', userRoutes);
var options = { method: 'POST',
url: 'http://localhost:3000/users/db',
headers:
{ 'content-type': 'application/x-www-form-urlencoded',
'postman-token': '',
'cache-control': 'no-cache' },
form: { title: '000000', artist: 'blah blah', genre: 'rap' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
当我从Postman发出post命令时,我收到一条成功的帖子。这只是我返回JSON的方式吗?我希望能够看到数据库中每个帖子的标题,艺术家和流派。
由于
答案 0 :(得分:1)
在这种情况下,Mongoose根本无法保存您期望的内容。尝试在调试器中查看req.body
和tune1
,以确保您获得预期的结果。
在您的架构中将strict
设置为'throw'
也可能有所帮助,因此当我们尝试保存无效tune
时,我们会收到错误消息:
var track = new Schema({
title: String,
artist: String,
genre: String
}, {
strict: 'throw'
});