Open a connection and share that between your routes/services. You can initialize the db and all related schema before you start express.
import mongoose from 'mongoose';
// define models
import User from './user';
import Order from './order';
// connect to db
const connect = async () => {
await mongoose.connect(process.env.DATABASE_URL);
return mongoose.connection;
};
const models = { User, Order };
export { connect };
export default models;
Then connect before you startup Express:
import models, { connect } from './models';
...
// connect to the db
const connection = await connect();
// now pass in the models to your routes
request('./routes/users')(models);
request('./routes/orders')(models);
// or use middleware so you can access in routes like req.models.user.find({})
app.use((req, res, next) => {
req.models = models;
next();
})
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);
You can add a cleanup handler to listen to process.exit and close the connection there. Roughly something like:
const cleanUp = (eventType) => {
connection.close(() => {
console.info('closed');
});
};
[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
process.on(eventType, cleanUp.bind(null, eventType));
})