如何在nodejs应用程序中输出mongodb集合以获得响应

我正在使用Cloude 9环境来开发我的nodejs应用程序。 在那里我写了代码连接到mongodb数据库。 我成功地连接到数据库并添加logging到集合。

现在我想发送收集信息作为回报。 但是使用res.send(collectionInfo); 不pipe用。

让我知道我该怎么做到这一点

以下是我的server.js文件的代码

 var Db = require('mongodb').Db; var http = require('http'); var path = require('path'); var async = require('async'); var socketio = require('socket.io'); var express = require('express'); var ejs = require('ejs'); var app = express(); var helpers = require('express-helpers') var MongoClient = require('mongodb').MongoClient; var Server = require('mongodb').Server; var db; helpers(app); var bodyParser = require('body-parser'); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded var server = http.Server(app); server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () { var addr = server.address(); console.log("Chat server listening at", addr.address + ":" + addr.port); }); app.use(express.static(__dirname + '/public')); app.set('views', __dirname + '/public/views'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); //app.use(express.static(__dirname + '/client')); app.use(express.static(path.join(__dirname, '/client'))); // MongoDB Connection app.use(function(req, res, next) { next(); }) app.get('/monogdb', function (req, res) { res.render('monogdb.ejs'); }); app.post('/ajax-mongo-connect', function (req, res) { var mongoClient = new MongoClient(new Server('localhost', 27017)); mongoClient.open(function(err, mongoClient) { if(err){ console.log(err); }else{ var db = mongoClient.db("mydb"); db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } ); console.log('database connected',db); var collectionInfo = db.collection("students"); mongoClient.close(); //res.setHeader('Content-Type', 'application/json'); res.send(collectionInfo); } }) }) 

根据@Roman Sachenko的回答,我试图使用res.send(collectionInfo.toJSON()); 但它是给出下面的错误

 /home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299 throw err; ^ TypeError: Object #<Collection> has no method 'toJSON' at /home/ubuntu/workspace/server.js:66:41 at MongoClient.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5) at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11) at process._tickCallback (node.js:442:13) 

并使用res.send({data: collectionInfo}); 给出错误

 home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299 throw err; ^ TypeError: Converting circular structure to JSON at Object.stringify (native) at ServerResponse.res.json (/home/ubuntu/workspace/node_modules/express/lib/response.js:185:19) at ServerResponse.res.send (/home/ubuntu/workspace/node_modules/express/lib/response.js:117:21) at /home/ubuntu/workspace/server.js:67:21 at MongoClient.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5) at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11) at process._tickCallback (node.js:442:13) 

尝试返回这个: res.status(200).json({'myCollection' : collectionInfo});

你可以在这里find更多关于快速回复的细节

更新:

在解释详细信息之后,请看下面的代码:

 app.post('/ajax-mongo-connect', function (req, res) { var mongoClient = new MongoClient(new Server('localhost', 27017)); mongoClient.open(function(err, mongoClient) { if(err){ console.log(err); res.status(500).json({message : 'OMG, an error occurred'}); }else{ var db = mongoClient.db("mydb"); db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } ); console.log('database connected',db); var collectionInfo = db.collection("students"); // Here we will find all students collectionInfo.find({}).toArray(function(err, students) { // so now, we can return all students to the screen. res.status(200).json({'myCollection' : students}); } } }) }) 

干杯!

mongooseODM

首先我想推荐你使用Mongoose ODM: https : //github.com/Automattic/mongoose

所以你会让你更容易的使用数据库。

基本上它返回(Mongoose)正常对象作为结果,但在遇到问题时,您可以尝试使用toObject()toJSON()或如上所述创build自己的对象,像{data: mongoCollection}

例子:

 res.send(collectionInfo.toObject()); res.send(collectionInfo.toJSON()); res.send({data: collectionInfo}); 

如有疑问,请参考链接:

http://mongoosejs.com/docs/guide.html#toJSON

本机驱动

至于本地驱动程序,它也应该返回正常构造的对象,但根据我以前遇到的问题,如果您手动设置标题JSON.stringify总是有帮助。

你也可以检查你的实体的内容。 所以你可以只输出它console.log(collectionInfo);

那么只要确保里面有正确的对象。 根据结果​​,你可以采取如下行动:

  • res.send(JSON.stringify(collectionInfo)) //set headers manually
  • res.json(JSON.stringify(collectionInfo)) //you don't need to set headers

至less你会知道什么是在里面的collectionInfo。 我认为这将足以调查这个问题。

您可以通过在node.js中执行以下操作来查看循环JSON对象:

  const util = require('util') // Native node module util.inspect(circularObj) 

你可以从代码的任何地方调用它,所以它是非常灵活的。