Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set up different node.js environments with different mongo databases?

I want to use a local mongo server in development and then switch to a mongolab db in production. What is the recommended way to do this in a node.js express app? All I know is that NODE_ENV exists but not sure on the best way to switch the database based on its value. Having:

if (process.env.NODE_ENV == "production") 
{
  //
}
else if ((process.env.NODE_ENV == "development") 
{

}

All over the place where I query the db doesn't seem very elegant. Is there a way to do it similar to a rail app where you specify you adapter for production and development?

like image 964
nickponline Avatar asked May 22 '12 16:05

nickponline


1 Answers

You should only need to connect to your DB using a URL once at application start time, and there you can use code like you have to choose the correct URL based on the runtime environment. Once connected, you app should reference a shared database connection object to perform queries and operations as normal. You may want to handle this with a configuration object as I describe in ExpressJS How to structure an application?

like image 87
Peter Lyons Avatar answered Oct 15 '22 08:10

Peter Lyons