Search code examples
node.jsmongodbcloud9-ide

Page hangs while doing operation on MongoDb database


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. But when I try to do operations on database the page becomes not responsive and hangs.

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.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");
            console.log('database connected',db);
            mongoClient.close();
        }
    })
})

Note that from my view page I am calling action ajax-mongo-connect with POST method. To call goes to app.post('/ajax-mongo-connect'... but page becomes irresponsible and hangs.

Let me know what I am doing.


Solution

  • You need to return something in your /ajax-mongo-connect route, for example res.send('its working dude!'); or call the next() function.

    Cheers!