Syntle
Syntle

Reputation: 5174

Properly closing a connection once done with query

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

Upvotes: 0

Views: 53

Answers (1)

Cheetara
Cheetara

Reputation: 539

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

Upvotes: 1

Related Questions