Properly close mongoose's connection once you're done

node.jsMongodbMongoose

node.js Problem Overview


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 ?
mongoose.connect('mongodb://localhost:27017/somedb'); 

// 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: https://groups.google.com/group/mongoose-orm/browse_thread/thread/c72cc1c51c76e661

Thanks

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.

node.js Solutions


Solution 1 - node.js

You can close the connection with

mongoose.connection.close()

Solution 2 - node.js

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

Solution 3 - node.js

You can set the connection to a variable then disconnect it when you are done:

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

// Do some stuff

db.disconnect();

Solution 4 - node.js

Just as Jake Wilson said: You can set the connection to a variable then disconnect it when you are done:

let db;
mongoose.connect('mongodb://localhost:27017/somedb').then((dbConnection)=>{
    db = dbConnection;
    afterwards();
});


function afterwards(){

    //do stuff

    db.disconnect();
}

or if inside Async function:

(async ()=>{
    const db = await mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: 
                  true })

    //do stuff

    db.disconnect()
})

otherwise when i was checking it in my environment it has an error.

Solution 5 - node.js

I'm using version 4.4.2 and none of the other answers worked for me. But adding useMongoClient to the options and putting it into a variable that you call close on seemed to work.

var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })

//do stuff

db.close()

Solution 6 - node.js

You will get an error if you try to close/disconnect outside of the method. The best solution is to close the connection in both callbacks in the method. The dummy code is here.

const newTodo = new Todo({text:'cook dinner'});

newTodo.save().then((docs) => {
  console.log('todo saved',docs);
  mongoose.connection.close();
},(e) => {
  console.log('unable to save');
});

Solution 7 - node.js

mongoose.connection.close(function(){
console.log('Mongoose default connection disconnected through app termination;);
process.exit(0);
});

This will close the mongoose connection and will also notify you by message in your console.

Solution 8 - node.js

Probably you have this:

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

// Do some stuff

db.disconnect();

but you can also have something like this:

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

const model = mongoose.model('Model', ModelSchema);

model.find().then(doc => {
  console.log(doc);
}

you cannot call db.disconnect() but you can close the connection after you use it.

model.find().then(doc => {
  console.log(doc);
}).then(() => {
  mongoose.connection.close();
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLepidosteusView Question on Stackoverflow
Solution 1 - node.jsKenanView Answer on Stackoverflow
Solution 2 - node.jsgeaw35View Answer on Stackoverflow
Solution 3 - node.jsJake WilsonView Answer on Stackoverflow
Solution 4 - node.jsadir abargilView Answer on Stackoverflow
Solution 5 - node.jstumeloView Answer on Stackoverflow
Solution 6 - node.jsRamanand PrajapatiView Answer on Stackoverflow
Solution 7 - node.jsZohaib AmirView Answer on Stackoverflow
Solution 8 - node.jsabranheView Answer on Stackoverflow