Reputation: 77
Consider this code snippet below which is in the A.js file.
const connection = {};
mongo_cli.connect(url, (err, db) => {
...
connection['con'] = db;
});
module.exports = {
mongo:{
connection: connection['con'];
}
}
I do this const database = require('./A').mongo.connection;
in B.js. A and B js files are in the same directory.
Why database variable in B file is undefined ?
Upvotes: 0
Views: 896
Reputation: 5007
This is a callback function:
(err, db) => {
…
connection['con'] = db;
}
It might get executed after the code that reads the database
variable in B.js.
Upvotes: 0
Reputation: 175
U won't get undefined if the connection succeeded. so for handling that , you can try something like this.
const connection = {};
connection['con'] = null;
mongo_cli.connect(url, (err, db) => {
...
connection['con'] = db;
});
module.exports = {
mongo:{
connection: connection['con']; // if connection failed then connection['con'] will be null.
}
}
Upvotes: 0
Reputation: 703
That's because connection['con'] = db
is in the execution context of the connect
function callback. If you access connection['con']
from outside you're likely to get undefined. I suggest you to use Mongoose for such implementations. Here is a simple example:
const mongoose = require('mongoose');
const url = "your_mongodb_url";
const connect = mongoose.connect(url, {
useNewUrlParser: true
});
connect.then((db) => {
console.log('Database Connected');
}, (err) => {
console.log(err);
});
Upvotes: 1