How to properly close Mongoose’s connection once it’s done ?

Sometimes, we want to properly close Mongoose’s connection once it’s done.

In this article, we’ll look at how to properly close Mongoose’s connection once it’s done.

How to properly close Mongoose’s connection once it’s done?

To properly close Mongoose’s connection once it’s done, we can use the mongoose.disconnect method.

For instance, we write

const db = mongoose.connect('mongodb://localhost:27017/somedb');

// ...

db.disconnect();

to call mongoose.connect with the database URL to connect to the database.

And then we call disconnect on the db handle to disconnect the database connection once we’re done.

Conclusion

To properly close Mongoose’s connection once it’s done, we can use the mongoose.disconnect method.