我试图使用express将数据放入mongodb中,但它始终存储空白...而且它不打印任何控制台日志:
启动服务器后我命中的网址是
http:// localhost:3000 / posts?title = test&link = http://test.com
它显示以下输出:
{“ __v”:0,“ _ id”:“ 562717b064002b1c2e697b33”,“评论”:[],“支持”:0}
router.get('/posts', function(req, res, next) {
console.log('reached ere '+req);
var post = new Post(req.body);
post.save(function(err, post){
if(err){ return next(err); }
res.json(post);
});
});
发布方案:
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
mongoose.model('Post', PostSchema);
您正在以以下方式调用您的API
http:// localhost:3000 / posts?title = test&link = http://test.com
这将发送title
和link
服务器作为查询参数,而不是身体参数。因此,req.body
在这种情况下,您将是一个空对象。这就是为什么没有数据被保存在您的帖子集中的原因。
您在这里有两个选择:
req.query
在帖子集合中,您可以执行以下操作:代替
var post = new Post(req.body);
和
var post = new Post(req.query);
link
和title
作为正文参数,而不是查询参数。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句