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