CJe
CJe

Reputation: 1992

node.js / mongodb file structure

I'm trying to set up this simnple NodeJS/mongodb app and I have my files structured like this:

server.js
    |
    +-routes/menu.js
    +-routes/cases.js

In my server.js I declare my mongodb vars like this:

var express = require('express'),
    mongo = require('mongodb'),
    Server = mongo.Server,
    MongoClient = mongo.MongoClient,
    Db = mongo.Db,
    http = require('http'),
    app = express(),
    httpServer = http.createServer(app),
    bodyParser = require('body-parser'),
    server = new Server('host.mongohq.com', 10066, {auto_reconnect : true}),
    db = new Db('myDb', server);

db.open(function(err, client) {
    client.authenticate('myUser', 'myPassword', function(err, success) {
        console.log('Authenticated');
    });
});
var cases = require('./routes/cases'),
    menu = require('./routes/menu');

But then when I try to reference my db var in eg menu.js like this:

db.collection(myCollection, function(err, collection) {});

I get an error that db is not defined.

Obviously I can move all the mongodb declarations down to both my menu.js and cases.js file but that's just very elegant. So how do I create one mongodb instance var and refer to it from my included files?

Thanks in advance...

Upvotes: 1

Views: 472

Answers (1)

Tony
Tony

Reputation: 2483

You need to require server.js in your menu.js file.

Your db object isn't global. If you want it to be, declare it without var.

Upvotes: 2

Related Questions