I was coding a leveling system for my discord bot, but encountered a mongoerror on the way, does anyone know why this is occuring? (The addXp function runs whenever someone chatted, the error is logged in the removeTimeout function.) I have used mongoose in many more ways in my code but this hasn’t yet occured before, I also did find others’ issues with this error but found no fitting solution there.
async function removeTimeout(leveldataid) { console.log("removetimeout") await mongo().then(async (mongoose) => { try { await levelSchema.findByIdAndUpdate( leveldataid, { _id: leveldataid, oncooldown: false }, {upsert: true} ) } catch(err) { console.log(err) } finally { mongoose.connection.close() } }) } async function addXP(member, guild) { let data = undefined let changedleveldata = false await mongo().then(async (mongoose) => { try { data = await levelenabledSchema.findById(guild.id) if (data) { if (data.enabled == true) { let extraxp = Math.floor(Math.random() *20) + 15 let leveldata = await levelSchema.findById(`guild${guild.id}member${member.id}`) if (!leveldata) { await levelSchema.findByIdAndUpdate( `guild${guild.id}member${member.id}`, { _id: `guild${guild.id}member${member.id}`, guild: guild.id, level: 1, maxXp: 113, xp: extraxp, oncooldown: true }, {upsert: true} ) } else { if (leveldata.oncooldown == false) { let newlevel = leveldata.level let newMaxXp = leveldata.maxXp newMaxXp = Math.floor(newMaxXp) let xp = leveldata.xp xp +=extraxp if (xp > leveldata.maxXp) { xp -=Math.floor(100*1.135**newlevel) newlevel++ newMaxXp = 100*1.13**newlevel } await levelSchema.findByIdAndUpdate( `guild${guild.id}member${member.id}`, { level: newlevel, maxXp: newMaxXp, xp: xp, oncooldown: true }, {upsert: true} ) } } } } changedleveldata = true } catch(err) { console.log(err) } finally { mongoose.connection.close() } if (changedleveldata == true) { setTimeout(remoteTimeout(`guild${guild.id}member${member.id}`), 60000) } }) }
Advertisement
Answer
This basically means the connection between node server and mongoDB was interrupted while writing data.
The solution to your problem would be to remove the finally
block from your code because it interrupts the connection when the bot is being used by a lot of users and the bot tries to write data while a previous connection is being closed.
await mongo().then(async (mongoose) => { try { // code here } catch(e) { console.log(e); } });