-
Notifications
You must be signed in to change notification settings - Fork 2
Fixing some MongoDB issues
canta slaus edited this page Mar 30, 2021
·
1 revision
This is meant as a quick help for those who followed some MongoDB tutorials by WornOffKeys and getting errors like:
Topology is closed
Operation ... buffering timed out after 10000ms
MongoError: server is closed
Short explanation: You're most likely continuously disconnecting and reconnecting to your database, which eventually will cause some errors.
It really is that simple and the fix is probably even simpler: Don't disconnect - only connect once and be done with it.
Your code might look like this:
await mongo().then(async (mongoose) => {
try {
await someSchema.findOneAndUpdate(query, update, options) // some schema operation here
} finally {
mongoose.connection.close()
}
})
Now, Don't disconnect - only connect once
: Remove all mongoose.connection.close()
as well as the await mongo().then()
part
Your code should then look something like:
await someSchema.findOneAndUpdate(query, update, options) // some schema operation here
But make sure that you have connected to the database once somewhere using the await mongo()
.