Return a promise from your config.js
file. mongodb client supports promises directly, just do not pass the callback parameter and use then
.
config.js
module.exports = (app) => {
const mongo_client = require('mongodb').MongoClient;
const assert = require('assert');
const url="mongodb://localhost:27017";
const db_name="portfolio";
return mongo_client.connect(url).then(client => {
assert.equal(null, err);
console.log('Connection Successfully to Mongo');
return client.db(db_name);
});
};
And call then and do the rest in the promise handler:
main.js
var express = require('express')
var app = express();
// Web server port number.
const port = 4343;
require('./config/app_config')(app).then(db => {
db.collection('users');
});
// as Bergi suggested in comments, you could also move this part to `then`
// handler to it will not start before db connection is estabilished
app.listen(port, () => {
console.log(`Server start at port number: ${port}`);
});
1
solved How can i get result from export module using async/await