Properly close mongoose's connection once you're done


I'm using mongoose in a script that is not meant to run continuously, and I'm facing what seems to be a very simple issue yet I can't find an answer; simply put once I make a call to any mongoose function that sends requests to mongodb my nodejs instance never stops and I have to kill it manually with, say, Ctrl+c or Program.exit().

The code looks roughly like this:

var mongoose = require('mongoose');

// if my program ends after this line, it shuts down as expected, my guess is that the connection is not really done here but only on the first real request ?

// define some models

// if I include this line for example, node never stop afterwards
var MyModel =  mongoose.model('MyModel', MySchema);

I tried adding calls to mongoose.disconnect() but no to result. Aside from that, everything works fine (finding, saving, ...).

This is the exact same issue as this person, sadly he did not receive any answer:


EDIT: accepted the answer below as it is technically correct, but if anyone ever hit this problem again, it seems that mongoose and/or the mongodb driver does not actually close the connection when you ask it to if there are still queries running.

It does not even remember the disconnect call at all, it does not do it once queries are finished running; it just discards your call with no exception thrown or anything of the sort, and never actually close the connection.

So there you have it: make sure that every query has been processed before calling disconnect() if you want it to actually work.

This question is tagged with node.js mongodb mongoose

~ Asked on 2012-01-11 03:37:26

The Best Answer is


You can close the connection with


~ Answered on 2012-01-11 03:57:59


The other answer didn't work for me. I had to use mongoose.disconnect(); as stated in this answer.

~ Answered on 2013-11-23 19:57:34

Most Viewed Questions: