0

I am not sure how to close the connection once I'm done with my query

mongoose.connect("mongodb://localhost:27017/Settings", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
});

SettingsModel.create({ guildID: guild.id } as Settings, (err: string, res: any) => {
    if (err) return console.error(err);
    console.log(res);
});
Syntle
  • 5,168
  • 3
  • 13
  • 34

1 Answers1

1

Unless there's a specific reason you want to close the connection, you shouldn't - Closing and opening connections is intensive and expensive. You open a connection once with and reuse it whilst your app is live.

It's advisable to close all connections when you shut down you app completely - you could do with

process.on('SIGINT', function() {
  mongoose.connection.close(function () {
    console.log('Disconnected db on app termination');
    process.exit(0);
  });
});
Cheetara
  • 529
  • 1
  • 6
  • 19
  • I am developing a discord bot and my problem is I always open a connection once someone runs a command let's say, how could I make it so I only have to open the connection once and reuse it until app termination? I would also like to know how I'd do so while also being able to access different parts of my db like `localhost:27017/Settings` and `localhost:27017/Servers` for example – Syntle Apr 02 '20 at 02:57
  • 1
    Check out this post which should help : https://stackoverflow.com/questions/23293202/export-and-reuse-my-mongoose-connection-across-multiple-models – Cheetara Apr 03 '20 at 18:37