3

I am new to MEAN stack. I am trying to retreive a list of documents from MongoDB. I have used Visual Studio 2013 community edition to create a basic Nodejs Express application. Visual studio created app.js file on the root for configuration. I have put following code in app.js which is relevant to mongodb:

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();
});

In the routes folder that visual studio created, I have created a js file which will perform CRUD operations. I have following code in this file:

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;

I am Type Error: Converting Circular structure to JSON.

I am trying to not using any schema.

Please advice.

learner
  • 581
  • 7
  • 27
  • 2
    `collection.find()` does not return the results. Check out some tutorials on how to use it. – NG. Jun 19 '15 at 19:29
  • thanks, do you have any link for tutorial which does not use any schema (mongoose or any other) for using MEAN stack? I have been trying for few days but couldn't find any. – learner Jun 19 '15 at 19:52

1 Answers1

12

For those of you, who encounter the similar problem, find() doesn't return the document, we need to use toArray to retrieve documents. Following code did the trick:

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();
            });
        });
    });
});
learner
  • 581
  • 7
  • 27