熊没有正确创建

时间:2017-02-11 20:22:29

标签: node.js mongodb express mean-stack

我正在使用this Scotch文章构建我的第一个MEAN堆栈应用程序。

我已经达到了向POST发送localhost请求以通过Postman创建新熊(模型)的程度。

问题在于,当我发送查看所有熊的请求时,我会回复以下内容:

[
  {"_id":"589f6ecc734d1d56393c9444","name":"Klaux"},   
  {"_id":"589f6f924af04a03d8870dea","__v":0}
]

数组中的第一个对象是我在创建新document时手动在MongoDB中创建的示例。如上所述,当我通过Postman发送创建请求时,它没有正确创建(数组中的第二个对象。)

这是发送请求的代码:

// /api/bears
router.route('/bears')
  .get(function(req, res) {
    Bear.find(function(err, bears) {
      if (err)
        res.send(err);
      console.log('Bears',bears);
            res.json(bears);
    });
  })
  .post(function(req, res) {
    var bear = new Bear();      // create a new instance of the Bear model
    bear.name = req.body.name;  // set the bears name (comes from the request)

    // save the bear and check for errors
    bear.save(function(err) {
      if (err)
        res.send(err);
            res.json({ message: 'Bear created!' });
    });
});

app.use('/api', router);

数据库集合如下所示:

MongoDB mLab

那么为什么没有正确创建记录?

修改

熊模型看起来像这样:

var mongoose   = require('mongoose');

var BearSchema = new mongoose.Schema({
  name: String
});
module.exports = mongoose.model('Bear', BearSchema);

1 个答案:

答案 0 :(得分:0)

实际上,在文章底部的评论部分回答了这个问题。 这是一个总结:

Postman发送时,x-www-form-urlencoded的选项不应设置。 相反,它应设置为raw并传递为JSON。请参见下面的屏幕截图:

enter image description here

相关问题