ChatGPT解决这个技术问题 Extra ChatGPT

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 ?
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.

Is there a way to do this just from importing a model? neither of the below answers work : \
I can't tell from the question if you have tried it, but it should work (i.e. close the connection) if you apply Kenan's solution inside an asynchronous function after awaiting the queries.

K
Kenan

You can close the connection with

mongoose.connection.close()

This does in fact close the connection. However this call was clearing the contents in my database. When I switched to mongoose.disconnect() everything worked properly and my mocha tests started working properly again
This worked for me. I just needed to make sure I placed this in the correct callback or else it probably was closing the connection before saving to the database had a chance to finish. To be fair, I'm still using a simple script that just connects to the local db and saves a simple example user object. In the callback to user.save() is where I call mongoose.connection.close().
As you can see, these answers are old. If you're using Mongoose 5.0.4, the Connection.close() method is only exported, only available, so use it.
@BrianNoah what do you mean "this call was clearing the contents in my database"? mongoose.connection.close()? is there an explanation for this behaviour? is this a bug in mongoose that's been fixed now, or..?
C
Community

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


This is also preferred when tearing down a testing environment.
mongoose.disconnect() is better to use and a logical approach.
In my test environment using Jest this properly cleaned everything up, while I was still having open handles when calling mongoose.connection.close().
J
Jake Wilson

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();

In my situation (testing Mongoose inside Jest) this is the only solution that worked
I do Model.update(..) with Mongoose within a for-loop. Is it necessary to close connection after every update? My server has to handle a lot of updates and stopped working after a while.
Same answer as below
a
adir abargil

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.


t
tumelo

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()

deprecated in mongoose 5.x
its better to user mongoose.disconnect()
D
Dharman
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.


This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
a
abrahamcalf

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');
});

a
abrahamcalf

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();
});