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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With