I have been trying to make a web app using node.js and express and decided to work with mongodb. I am using mongodb node.js driver version: 4.3.1 I have tried all the possible ways to connect the node.js server with my mongodb atlas database.
const app = require('./app');
const MongoClient = require('mongodb').MongoClient
const Url = 'mongodb+srv://todoAppUser:<myOriginalPasswordHere>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority';
MongoClient.connect(Url, function (err, client) {
if (err) throw err;
var db = client.db('myDatabase');
db.collection('products').findOne({}, function (findErr, result) {
if (findErr) throw findErr;
console.log(result.name);
client.close();
});
});
This can't work, because modules are evaluated synchronously. Your callback is called asynchronously but your module has been alread evaluated at this time. Means module.exports
has no effect and require('./db').collection()
is not defined. Please see Node.js Modules for details.
To solve your problem, handle the connection stored in a module internal variable and export a getter instead of the connection variable itself.
// db.js
let client;
let db;
function connectDB(url, dbName) {
client = new MongoClient(url);
return new Promise(function(resolve, reject) {
client.connect(function(err) {
if(err) return reject(err);
db = client.db(dbName);
return resolve(db);
});
});
}
function getCurrentDB() {
return db;
}
module.exports.connectDB = connectDB;
module.exports.getCurrentDB = getCurrentDB;
Then reuse your opened connection in other files like the following:
// other.js
const db = require("./db.js");
db.getCurrentDB().collection("product");
Of course, getCurrentDB()
can only return a database connection if a connection has been established via connectDB()
beforehand. So you have to wait for the resolution of the Promise .
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.