-1

I have a node.js file which is the following:

var express = require('express');
var app = express();

var mongoClient = require('mongodb').MongoClient;


app.get('/',(req, res)=>{
    console.log(connectDB());
    res.send('get works');
 })


app.listen(3000,(err)=>{
if (err) {
    console.log(err);
}else{
    console.log('Connected to server @: 3000');
}
})

function connectDB(){
{
mongoClient.connect(url,{ useNewUrlParser: true },(err, client)=>{
        if(err){
            return false;      
        }else{
              return true;            
        }
    }) 
}
}

My issue is connectDB() is returning 'undefined'.If there was an error then it should return false else true, but it sends undefined. Why is that?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Aziz Qureshi
  • 281
  • 2
  • 4
  • 14

1 Answers1

0

Try this:

(async function() {
  try {

    const client = await MongoClient.connect(uri,{ useNewUrlParser: true });
    // ... anything

    client.close();
  } catch(e) {
    console.error(e)
  }

})()
Robert
  • 78
  • 1
  • 8