Reputation: 1556
I'm trying to save a function return in a const because I would be able to use informations outside of the function. To illustrate more my problem here's a piece of code.
const express = require('express')
const app = express()
var routes = require('./routes/routes');
var bodyParser = require('body-parser')
var MongoClient = require('mongodb').MongoClient;
const dbb = MongoClient.connect("mongodb://user:[email protected]:37600/tasksdb", { useNewUrlParser: true }, function (err, db) {
if (!err) {
console.log(db.db().databaseName);
}
else {
console.log(err)
}
});
app.use('/', routes);
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(3000, function () {
console.log("second", dbb);
console.log('Example app listening on port 3000!')
})
Here's what I get in terminal :
second undefined
Example app listening on port 3000!
tasksdb
How can I get db information outside of MongoClient.connect
function so that I could pass them to routes module ?
Upvotes: 0
Views: 239
Reputation: 894
Firstly be careful while copy pasting code on a platform,remove passwords if any in the code, infact mongoURL should be in .env file not in the main js.
MongoClient.connect() is an asynchronous call, therefore when the line
console.log("second", dbb);
is executed, MongoClient.connect() is still pending
To make it synchronous there are multiple solutions:
MAKE USE OF THE CALLBACK
const dbb = MongoClient.connect("mongodb://user:[email protected]:37600/tasksdb", { useNewUrlParser: true }, function (err, db) {
if (!err) {
console.log(db.db().databaseName);
app.listen(3000, function () {
console.log("second", dbb);
console.log('Example app listening on port 3000!')
})
}
else {
console.log(err)
}
});
now the console.log will only be executed when the mongoose.connect has finished
ASYNC AWAIT if you have nodejs >= 7.10.1 , your nodejs support Async await , you can check here
(async function init() {
const dbb = await MongoClient.connect("mongodb://user:[email protected]:37600/tasksdb", {
useNewUrlParser: true
});
if(dbb){
app.use('/', routes);
app.use(bodyParser.urlencoded({
extended: true
}));
app.listen(3000, function() {
console.log("second", dbb);
console.log('Example app listening on port 3000!')
})
}
})();
this solution is more readable.
Upvotes: 1