1

I have worked to node js + mysql. but now i am going to node js + mongoDB I am in need to connect database and make a variable for globally use. I am very much confused how we can define variable for globally use.

var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/mydb';

MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    //HURRAY!! We are connected. :)
    console.log('Connection established to', url);

    // do some work here with the database.


    db.close();
  }
});
Shadow
  • 33,525
  • 10
  • 51
  • 64
iam
  • 973
  • 4
  • 11
  • 21
  • Possible duplicate of [node.js global variables?](http://stackoverflow.com/questions/5447771/node-js-global-variables) – Shadow Feb 26 '16 at 09:14
  • how can i make db for globally use?? this is in function.. – iam Feb 26 '16 at 09:15
  • @iam check out the accepted answer [here](http://stackoverflow.com/questions/10656574/how-to-manage-mongodb-connections-in-a-nodejs-webapp) – vladzam Feb 26 '16 at 09:19

0 Answers0