I have initialized the connection to my mongodb and now export the db to other nodejs files. How can I do that?
i thought of something like this but it is giving errors.
let database;
export const connectDB = async () => {
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};
export default database
Error : undefined value of database
database will always be null when you import it.
connectDB is aync call by the time it executes your database variable is already loaded as null.
connectDB you can return database from here.
export const connectDB = async () => {
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
return database; // you can get from here
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};
export const connectDB = async () => {
if (database) return database; // return if database already connected.
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
return database; // you can get from here
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};