Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Samuel Ferree
Samuel Ferree
31,722 Points

Where and how to manage seperate mongoDB connectiosn for different environments in Express app?

I'm building an Express application, connecting to MongoDB through mongoose.

I want to connect to a different database when executing automated tests, than when I fire up the app on my dev environment (and will likely want a connection string for stage, and production in the future)

I've got before and after hooks in my mocha tests that seed/drop the database collections as needed, so I don't want to use the same database connection for dev and test.

I've reached a problem with my second test-file that attempts to connect to the test database. Iget the error "Trying to connect to an unclosed connection"

I assume this is because mongo only wants to connect once to a database.

I've seen where some people connect to the database in a file called db.js, and the require this module in all of their model files, but then my dev and test environments would be pointed at the same database.

Is there a way that I can set up db.js so that when running npm test, I connect to a different database than npm start?