2015-06-19 221 views
1

我是MEAN堆棧的新手。我正在嘗試從MongoDB中檢索文檔列表。我已經使用Visual Studio 2013社區版來創建一個基本的Nodejs Express應用程序。 Visual Studio在根上創建app.js文件進行配置。我已經把下面的代碼app.js這是有關的MongoDB:MongoDB和Express:類型錯誤:將圓形結構轉換爲JSON

var mongo = require('myDB'); 
var db = new mongo.Db("myDB", new mongo.Server("localhost", "27017"), 
{ safe: true }, { auto_reconnect: true }); 

// Make our db accessible to our router 
app.use(function (req, res, next) { 
    req.db = db; 
    next(); 
}); 

在路由文件夾是Visual Studio創建的,我創建了一個js文件將執行CRUD操作。我在此文件中下面的代碼:

var express = require('express'); 
var router = express.Router(); 
router.get('/myRecords', function (req, res) { 
    var db = req.db; 
    db.open(function (err, db) { 
     if (err) 
      console.log(err); 
     else {   
       var collection = db.collection('myCollection');     
       var dataToSend = collection.find(); 
       res.send(dataToSend);    
     } 
     })  
    }); 
module.exports = router; 

我類型錯誤:轉換圓形結構,以JSON。

我想不使用任何模式。

請指教。

+2

'collection.find()'不返回結果。查看一些關於如何使用它的教程。 –

+0

謝謝,你有沒有使用任何模式(貓鼬或任何其他)使用MEAN堆棧的教程的任何鏈接?我一直在嘗試幾天,但找不到任何。 – learner

回答

7

對於那些你,誰遇到了類似的問題,找到()不返回文檔,我們需要使用指定者來檢索文件。下面的代碼做的訣竅:

router.get('/myRecords', function (req, res) { 
    var db = req.db; 
    db.open(function (err, db) { // <------everything wrapped inside this function 
     db.collection('myCollection', function (err, collection) { 
      collection.find().toArray(function (err, items) { 
       res.send(items); 
       db.close(); 
      }); 
     }); 
    }); 
}); 
+0

有沒有辦法在這之後將它作爲JSON返回? – 221b

相關問題