Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use `mongoose.disconnect()` or `db.close()`

I am new to MongoDB. Now I am using Mongoose to take care of the database in my express.js app. My question is that I don't know when should I close the connection? Since someone says better to close it, while someone else says to leave it open? And what is the difference between db.close() and mongoose.disconnect()? What is your experience of using these?

Thanks!

like image 698
Yingqi Avatar asked Oct 31 '25 15:10

Yingqi


1 Answers

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));
})
like image 128
Samuel Goldenbaum Avatar answered Nov 02 '25 23:11

Samuel Goldenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!