Home > database >  How to pass database connection in NodeJS
How to pass database connection in NodeJS

Time:03-29

I'm using the express framework in NodeJS with typescript in the backend. I have a very easy architecture in my index file:

index.html

import express          = require("express");
import mongoClient      = require("mongodb");

import apiRoutes from "./routes";
import { MONGO_CONNECTION } from "./config/mongo_config";

const app = express();    

mongoClient.MongoClient.connect(MONGO_CONNECTION, { }, (err: any, mclient: any) => {
    if (err) throw err;

    const mongodb = mclient.db('test');

    app.use('/api', isOnline, apiRoutes);

    app.listen(80, () => console.log('API running on port 80'));
});

The express routes are separated in an other file (in my version it is separated in multiple file, just to keep it simple), here just an example:

routes/index.ts

import express          = require("express");
import { Router } from "express";

const router = Router({mergeParams: true});

router.get('/example', (req: express.Request, res: express.Response) => {
    res.json('Hello World');
});

export default router;

I don't want to use mongoose. So is there any way to pass the DB connection to another file without connecting again?

CodePudding user response:

You can export an object in your index.js

export const mongodb = {};

And then instead of this:

const mongodb = mclient.db('test');

Use:

mongodb.connection = mclient.db('test');

or something like this.

Then other parts of the code can import it but make sure that it is not undefined before you use it because it may have not been initialized yet.

Another option would be to export a promise that would be resolved with a connection established:

export const mongodb = new Promise((resolve, reject) => {
  // establish your connection here ...

  resolve(mclient.db('test'));

  // ...
);

And then in your importing code you will also use it with await.

  • Related