I have a very simple "server.js" setup that I am trying to run:
var express = require('express'),
wines = require('./routes/testscripts');
var app = express();
app.get('/first_test', wines.popSingleData);
app.listen(3000);
console.log('Listening on port 3000...');
This is set up to connect to localhost:3000
When I navigate to localhost:3000/first_test
, it calls the "popSingleData" method within testscript.js:
...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
console.log('include called');
exports.popSingleData = function(req, res) {
// var mongoose = require('mongoose');
// mongoose.connect('mongodb://localhost/test');
// var db = mongoose.connection;
console.log('function called');
db.on('error', console.error.bind(console, 'connection error:'));
console.log('error handler set');
db.once('open', function callback () {
//yay!
console.log("DB Opened");
var someSchema = require('../models/someSchema');
someSchema.find(function (err, found){
if (err)
{
console.log('err');
}
if(found.length != 0)
{
console.log("Found Data:");
console.log(found);
for( var i = 0; i < found.length; i++)
{
res.jsonp((found[i]));
}
}
});
});
};
...
The lines that are causing issue are the first 3:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
When they are declared within the function, the script runs as expected, printing out JSON objects it found from the database. When they are defined within testscript.js, but outside the scope of the method, the program hangs on the db.once('open', function callback () {...}); command
.
Could someone shed some light on the difference that occurs from moving these 3 lines of code? Do I really need to make a new connection every time I want a different function to access the database?