2016-12-01 81 views
0

我在使用猫鼬保存在Express nodejs中创建的对象时遇到了一些问题。Express Mongoose不保存数据

它总是说它已保存,但即使我登录到服务器并尝试自己获取它,也永远无法找到对象。

快递航线,以节省的MongoDB:

router.post('/share', function(req, res, next){ 
    //console.log('Post Request Made', req); 

    //switch to be inputed as parameters of the request 
    //save share 
    var share = new Shares({ link: req.body.link, description: req.body.description }); 
// var share = new Shares({ req.data.link, req.data.description }); 
    console.log('request body', req.body); 
    console.log('to be added', share); 
    //save to database 
    share.save(function(err, share){ 
     if(err){ 
      console.log(err); 
     } else { 
      console.log('the object was saved' , share); 
     var id = share._id; 
     res.send(id); 
     } 
    }); 
}); 

控制台日志:

request body { link: 'test', description: 'test' } 
to be added { link: 'test', 
    description: 'test', 
    _id: 5840b0393181d4000f652cba, 
    clicks: 0 } 
the object was saved { __v: 0, 
    link: 'test', 
    description: 'test', 
    _id: 5840b0393181d4000f652cba, 
    clicks: 0 } 
POST /share 200 73.618 ms - 26 
This is the link page with id: 5840b0393181d4000f652cba 
found [] 
GET /fluff/link/5840b0393181d4000f652cba 200 20.387 ms - 266 

配置:

var mongoose = require('mongoose'); 
mongoose.Promise = global.Promise; 
mongoose.connect('mongodb://mongo/shares'); 
require('./models/Shares'); 
+0

你检查蒙戈DB看到它保存与否? – BlackMamba

+0

我刚刚解决了它。我没有更改数据库以确保我在正确的区域之后,我打开猫鼬调试选项,然后正确的查询方法将发布我的答案了一下。 –

回答

0

解决的问题。我的问题是,我一般是mongo shell和mongodb的noob。

我实际上正确保存,但我在mongo shell中搜索的方式是错误的。如果您没有参数运行mongo,我没有意识到每次在mongo shell中它都会从test数据库中启动。

所以第一件事就是输入你想成为数据库:

`mongo [database_name]` 

然后检查是否有文件在那里:

`db.collections.count()` 
    `db.collections.find()` 

我真正的问题是,我Shares.findById()是错了,我不得不查找适当的参数。

这是什么工作版本貌似现在:

Shares.findById(id.toString(), function(err, share){ 
    if(err){ 
      console.log('error', err); 
     } else { 
      console.log('found', share); 
     } 
    });