Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  167] [ 6]  / answers: 1 / hits: 5575  / 10 Years ago, sat, july 12, 2014, 12:00:00

I have multiple routes that need to access a database, for development I use a local database, and obviously production I use a hosted database



The only problem is every time I go to push a release I have to go through each route manually changing the database link



e.g.



var mongodb = require('mongojs').connect('urlhere', ['Collection']);



It would be nice if I could declare a variable in app.js like



app.set('mongoDBAddress', 'urlhere');



then in each file do something like
var mongodb = require('mongojs').connect(app.get('mongoDBAddress'), ['Collection']);



Does anybody know if this is achievable I've been messing around with it for about an hour googling and trying to include different things but I have no luck. thanks.


More From » node.js

 Answers
9

From the docs:




In browsers, the top-level scope is the global scope. That means that
in browsers if you're in the global scope var something will define a
global variable. In Node this is different. The top-level scope is not
the global scope; var something inside a Node module will be local to
that module
.




You have to think a bit differently. Instead of creating a global object, create your modules so they take an app instance, for example:



// add.js
module.exports = function(app) { // requires an `app`
return function add(x, y) { // the actual function to export
app.log(x + y) // use dependency
}
}

// index.js
var app = {log: console.log.bind(console)}
var add = require('./add.js')(app) // pass `app` as a dependency

add(1, 2)
//^ will log `3` to the console


This is the convention in Express, and other libraries. app is in your main file (ie. index.js), and the modules you require have an app parameter.



You can add a global variable to GLOBAL, see this this question, although this is probably considered bad practice.


[#43929] Friday, July 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nadineannabellet

Total Points: 464
Total Questions: 94
Total Answers: 97

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
;