Reputation: 3
Long story short, I would like the object exported from myModule
to be created only after the first script is connected to the db; and then share myObject
with any scripts that need it. Can this be done? What are the smarter alternatives to do the same things?
//mainapp.js
const mongoose = require('mongoose');
/*application setup stuff*/
mongoose.connect(/*...*/);
//myModule.js
const mongoose = require('mongoose');
class myClass {
constructor(){
/*db operations*/
this.myVar = /*...*/;
}
}
module.exports = new myClass();
//script.js,script2.js,script3.js...
import myObject = require('./myModule');
/*...*/ = myObject.myVar;
Upvotes: 0
Views: 90
Reputation: 1985
I would like the object exported from myModule to be created only after the first script is connected to the db
You can start the server only if the the database connection was successfully established.
const app = express();
mongoose.connect(/*...*/).then(() => {
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);
}).catch((err) => console.error(err));
Upvotes: 1