its code i have;
const { MongoClient } = require("mongodb");
var db = null // global variable to hold the connection
var url = 'mongodb://0.0.0.0:27017/'
var dbName = 'mydb'
MongoClient.connect(url, (err, client) => {
if (err) {
console.error(err)
} else {
db = client.db(dbName) // once connected, assign the connection to the global variable
console.log(db)// show result
}
})
console.log(db) //result null
how to access 'db' variable in app.js or other module
this script in app.js
var db = require('./mongo.js')
console.log(db); //result empty string
To connect to a MongoDB database in Node.js version 18.13.x using MongoDB version 6.0, you can use the MongoDB driver for Node.js.
npm install mongodb
const MongoClient = require('mongodb').MongoClient;
global.db;
4.Then, you can use the MongoClient.connect() method to connect to your MongoDB database, passing in the connection URL and a callback function to handle any errors or successful connections.
MongoClient.connect('mongodb://<host>:<port>/<dbname>', {useNewUrlParser: true}, (err, client) => {
if(err) throw err;
global.db = client.db(<dbname>);
console.log("Connected to MongoDB");
});
global.db.collection('users').find().toArray((err, result) => {
console.log(result);
});
Make sure to replace host, port, and dbname with the appropriate values for your MongoDB setup.