javascript - Node.js + MongoDB global variable and scope -
i'm trying make single connection mongodb , store response (database) in global variable, can re-use in seperate js file (like separate files routes). i'm following documentation example: https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connection-pooling.
first try: var mongodb = require('mongodb'), mongoclient = mongodb.mongoclient, mongourl = "my_mongodb_url:port/database_name", global.db;
mongoclient.connect(mongourl, function(err, database) { db = databse; console.log(db); // shows stuff } console.log(global.db); // shows undefined
after research found possible fix problem: create global variable in node global prefix. it's still not working...
second try:
var mongodb = require('mongodb'), mongoclient = mongodb.mongoclient, mongourl = "my_mongodb_url:port/database_name", global.db; mongoclient.connect(mongourl, function(err, database) { global.db = databse; console.log(db); // shows stuff } console.log(global.db); // shows undefined
the code above put in same file [app.js]. think has scope of mongoclient. i'm not sure. there way make work?
that's order-of-execution problem. mongoclient.connect(...)
call asynchronous. callback function you're passing not invoked until connection established. console.log(global.db)
have @ end, however, invoked immediately, before callback called.
you don't need explicitly make db
global here. variables defined in outer scope of module in global scope of module. attaching value global
makes available across modules, better way expose values between modules attach them exports
, can explicitly imported needed. if you're using db
within module, that's not necessary.
Comments
Post a Comment