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
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:
Now in order to use your db instance where you need it, simply import the getClientDb function and use its resolved return value.
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: