【问题标题】:inserting in mongo using express使用 express 插入 mongo
【发布时间】:2015-10-21 13:24:29
【问题描述】:

我正在尝试使用 express 将数据放入 mongodb,但它始终存储空白......而且它没有打印任何控制台日志:

启动服务器后我点击的网址是

http://localhost:3000/posts?title=test&link=http://test.com

它显示以下输出:

{"__v":0,"_id":"562717b064002b1c2e697b33","cmets":[],"upvotes":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);

【问题讨论】:

    标签: mongodb express


    【解决方案1】:

    您将 API 调用为

    http://localhost:3000/posts?title=test&link=http://test.com

    它将title 和link 作为查询参数而不是正文参数发送到服务器。因此,在这种情况下,您的 req.body 将是一个空对象。这就是没有数据保存在您的帖子集合中的原因。

    你有两个选择:

    1. 更改您的 API 以将 req.query 保存在帖子集合中,您可以执行以下操作:

    替换

    var post = new Post(req.body);
    

    与

    var post = new Post(req.query);
    
    1. 将link 和title 作为正文参数而不是查询参数传递。

    【讨论】:

      猜你喜欢
      • 2016-05-15
      • 2017-03-04
      • 2023-04-03
      • 2020-08-31
      • 2021-12-14
      • 1970-01-01
      • 2016-12-15
      • 2013-09-23
      • 2013-09-20
      相关资源
      最近更新 更多