简体   繁体   中英

how to connect and set global "db" variable in nodejs V18.13.x and mongodb V6.0

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.

  1. First, you need to install the MongoDB driver for Node.js in your project by running the following command:
npm install mongodb
  1. Next, you will need to import the MongoClient class from the MongoDB driver in your Node.js file:
const MongoClient = require('mongodb').MongoClient;
  1. Create a global variable for the database connection:
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");
});
  1. Once the connection is established, you can use the global.db variable to make queries to the database.
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM