2016-12-01 85 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); 
     } 
    });