2016-03-02 53 views
0
router.get('/wiki/:topicname', function(req, res, next) { 
    var topicname = req.params.topicname; 
    console.log(topicname); 




    summary.wikitext(topicname, function(err, result) { 
      if (err) { 
       return res.send(err); 
      } 
      if (!result) { 
       return res.send('No article found'); 
      } 
      $ = cheerio.load(result); 

      var db = req.db; 
      var collection = db.get('try1'); 
      collection.insert({ "topicname" : topicname, "content": result }, function (err, doc){ 
       if (err) { 
        // If it failed, return error 
        res.send("There was a problem adding the information to the database."); 
       } 
       else { 
        // And forward to success page 
        res.send("Added succesfully"); 
       } 
      }); 

     }); 

使用此代碼,我試圖將從維基百科獲取的內容添加到集合try1。消息顯示「成功添加」。但收集似乎是空的。數據未插入到數據庫中無法在快遞中輸入mongo數據庫中的數據

+0

會發生什麼事,當你'console.log'的文檔從插入? –

+0

它正確顯示內容 – Deesha

+0

在'collection.insert'內的回調中,檢查是否存在'doc' if(doc){「DOC:」+ JSON .stringify(doc)); }' –

回答

0

以正確的路徑啓動您的mongod服務器,即與您用於檢查收集內容的路徑相同的路徑。

sudo mongod --dbpath <actual-path>

+0

非常感謝。我的mongod服務器運行在不同的目錄中。 – Deesha

1

的數據必須在那裏,MongoDB的有【W:1,J:真正}寫在默認情況下關注的選項,以便它沒有一個錯誤只的回報,如果,如果有任何文檔到文檔是真正的插入插。

事情你應該考慮:

- 不要使用插入功能,其depricated使用insertOne,insertMany或bulkWrite。參考:http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insert

- 插入方法回調有兩個參數。錯誤,如果有錯誤和結果。結果對象有幾個屬性可用於插入結果測試之後,如:result.insertedCount將返回插入文檔的數量。

所以根據這些在你的代碼中,你只測試錯誤,但你可以插入零文件沒有錯誤。

另外它不清楚我在哪裏得到你的數據庫名稱。代碼中的以下內容是否正確?你確定你已經連接到你想要使用的數據庫嗎?

var db = req.db; 

你也沒有與附上您的屬性名「在你的插入方法插入應該是這個樣子:

col.insertOne({topicname : topicname, content: result}, function(err, r) { 
    if (err){ 
     console.log(err); 
    } else { 
     console.log(r.insertedCount); 
    } 
}); 
相關問題