skip to Main Content

I want to export the client.db() after the connection but the problem is that the default export must be at the top level of a file or module declaration.

this is my code.

import { MongoClient } from "mongodb";
import app from "./app.js";

const client = new MongoClient("connect to mongodb")

async function start() {
    await client.connect()
    export default client.db() 
    app.listen(3000, ()=> {
        console.log("Your server is running at port 3000")
    })

}

I tried to create a global variable and set it equal the client:db() inside the start() function, the export default get the variable as the initial value "undefined".

2

Answers


  1. Default exports should always be at the top level of a file or module declaration and there is no workaround about this.

    However, there is a solution for what are you trying to achieve by using the singleton pattern. You can read more about this pattern on the link below:

    Singleton Pattern

    Your main goal is to be able to export just a single instance of the client db and you want every part of your application to use that same instance.

    You can achieve this by using the below implementation:

    import {
      MongoClient
    } from "mongodb";
    
    const client = new MongoClient("connect to mongodb")
    
    let clientDb = null;
    
    async function getClientDb() {
    
      if (clientDb) return clientDb;
    
      await client.connect();
      clientDb = client.db();
    
      return clientDb;
    }
    
    
    export default getClientDb;

    Now in order to use your db instance where you need it, simply import the getClientDb function and use its resolved return value.

    Login or Signup to reply.
  2. In modules, you can actually use top-level awaits in most situations. Assuming there aren’t any weird cross-dependencies, you can do something like this:

    import { MongoClient } from 'mongodb';
    import app from './app.js';
    
    app.listen(3000, () => {
      console.log('Your server is running at port 3000.');
    });
    
    const client = new MongoClient('connect to mongodb');    
    await client.connect();
    export default client.db();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search