Properly export Atlas connection in Node JS

Hi, I’m new working with MongoDB Atlas and I want to know if is there any best practice or properly export and reuse the mongo connection in nodejs, im using the layered structure, so already have the app.js separate from the express server listening, the routes, controllers, models and dao but i dont know how to reuse the db connection from a separate file and where to import it.
(im using the mongodb native driver)


I suggest you to use Mongoose.

Generally, you should connect to database before you start the server. With Mongoose, you can just pass the connection string that you can fetch from Atlas. You should not hardcode that connection string because it should not be visible in your code, since your code will probably go in GitHub or somewhere where other people will be able to see it. The good practice is to create .env file and to add an environment variable there (MONGODB_CONNECTION_URL for example), which you can use later in your app without exposing actual secrets. For that, you can use popular dotenv package.

Once you connected to MongoDB with Mongoose, you can use Mongoose to query database anywhere in your application, and it will use the connection that you created when starting the server.

You can do it like this:

const express = require('express');
const mongoose = require('mongoose');

mongoose.connect(process.env.MONGODB_CONNECTION_URL).then(() => {

  const app = express();

  app.use(express.urlencoded({ extended: true }));
  app.use(express.static(path.join(__dirname, 'public')));

  // Add your endpoints

  const server = http.createServer(app);

  server.listen(process.env.PORT || 3000, () => {
    console.log(`Server is listening on port ${server.address().port}`);