javascript - MongoDB and Express: Type Error: Converting Circular structure to JSON -
i new mean stack. trying retreive list of documents mongodb. have used visual studio 2013 community edition create basic nodejs express application. visual studio created app.js file on root configuration. have put following code in app.js relevant 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 our router app.use(function (req, res, next) { req.db = db; next(); });
in routes folder visual studio created, have created js file perform crud operations. have following code in 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 type error: converting circular structure json.
i trying not using schema.
please advice.
for of you, encounter similar problem, find() doesn't return document, need use toarray retrieve documents. following code did trick:
router.get('/myrecords', function (req, res) { var db = req.db; db.open(function (err, db) { // <------everything wrapped inside function db.collection('mycollection', function (err, collection) { collection.find().toarray(function (err, items) { res.send(items); db.close(); }); }); }); });
Comments
Post a Comment