Question

I'm new to Node and Express and am having difficulty getting data out of my database in Express.

When run from console the first code example below runs and returns data, but when I try and do the same thing from within Express it doesn't work?

Using the /scores URI I cannot get anything back from the server. It just eventually times out.

Any help is greatly appreciated!

/**
 * Created by Mike on 2/1/14.
 */
var mongo = require('mongodb');
var connectionUri = "mongodb://app_user:xxxxxxx@troup.mongohq.com:10000/??????'";
var mongodb = require('mongodb'), MongoClient = mongodb.MongoClient;
MongoClient.connect(connectionUri, function (err, db) {
    if (err) throw error;

    var collection = db.collection('sessions');

    collection.findOne({}, function (err, doc) {
        if (err) throw err;

        console.log(doc.results);

        db.close();
    });
});

Here is the app.js Express code:

/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var mongo = require('mongodb');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/api', function(request, response) {
    response.send({name:"Raymond",age:40});
});
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/scores', routes.scores);
app.get('/sessions', routes.sessions);
//app.post('/session', routes.session(db));

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

And finally here is the routes/index.js file. (The connection string has been cleaned up)

/*
 * GET home page.
 */

exports.index = function (req, res) {
  res.render('index', { title: 'Express' });
};

exports.sessions = function (req,res) {
    "use strict";
    res.render('index', { title: 'Scores' });
};

exports.scores = function (db) {
    return function (req, res) {
        "use strict";
        var connectionUri = "mongodb://app_user:xxxxxxxxx@troup.mongohq.com:00000/??????";
        var mongodb = require('mongodb'), MongoClient = mongodb.MongoClient;
        MongoClient.connect(connectionUri, function (err, db) {
            if (err) throw error;

            var collection = db.collection('sessions');

            collection.findOne({}, function (err, doc) {
                if (err) throw err;

                res.render('scores', {
                    "scores": doc
                });

                db.close();
            });
        });
        /*var collection = db.get('sessions');
        collection.find({}, {}, function (e, docs) {
            res.render('scores', {
                "scores" : docs
            });
        });*/
    };
};
Was it helpful?

Solution

It looks like the function you are exporting for exports.scores is expecting the db object to be passed in.

exports.scores = function (db) {

Your app.js is just using that as the route handler and is passing req and res into it while it is expecting the db object. When the route gets hit all you are doing is returning a function.

For this to work you'll need to export the function you are currently returning.

exports.scores = function (req, res) {

Please Note!!!

You are creating a connection every time a request comes through that route. While you do close it at the end if the route becomes busy you are opening many pools of connections to your database unnecessarily. It is better to open a connection at a central point and then pass around the db object from there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top