简体   繁体   中英

How to save connection result in a variable in nodeJs

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:tpassword@ds137600.mlab.com: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 ?

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:tpassword@ds137600.mlab.com: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:tpassword@ds137600.mlab.com: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.

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