简体   繁体   中英

How to output mongodb collections in nodejs app to get them in response

I am using Cloude 9 environment for developing my nodejs app. In that I have written code to connect to mongodb database. I am successfully connecting to database and adding record to collection.

Now I want to send the collection info in return. But using res.send(collectionInfo); is not working.

Let me know how should I achieve this

Below is the code of my server.js file

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

        }
    })
})

As per @Roman Sachenko answer, I have tried to use res.send(collectionInfo.toJSON()); but it is giving below error

/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) 

and using res.send({data: collectionInfo}); gives error

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)

Try to return this: res.status(200).json({'myCollection' : collectionInfo}); .

You can find more details about express response here

Update:

After you explain the details, take a look at the code below:

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

Cheers!

Mongoose ODM

First of all I would like to recommend you using Mongoose ODM: https://github.com/Automattic/mongoose

So you will make you work with database much easier.

Basically it returns (Mongoose) normal object as results, but in case of issues you may try to use toObject() or toJSON() or as it mentioned create own object like {data: mongoCollection}

Examples:

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

Please refer to the link in case of questions:

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

Native Driver

As for native driver, it also should return normally-constructed object, but according to issues I faced with in the past, JSON.stringify always helps if you set headers manually.

You may also check the contents of your entity. So you can just output it by console.log(collectionInfo);

Then just make sure that there is correct object inside. And according to results you can take actions like:

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

At least you will know what exactly is inside of collectionInfo. I think it will be enough to investigate the issue.

You can view circular JSON objects by doing this in node.js:

 const util = require('util') // Native node module

 util.inspect(circularObj)

You can call it from anywhere in the code, so it's very versatile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM