MongoError: Topology is closed, please connect when making a discord.jsv12 mute command

MongoError: Topology is closed, please connect when making a discord.jsv12 mute command

我见过很多人遇到 Topology is closed 错误,但我从来没有见过一个直接的答案,它不仅回答了给出的确切代码片段的问题,而且大体上概述了拓扑结构及其工作原理。

我正在关注 YT 上的 WOK DiscordJSv12 教程,并从存储库中克隆了静音命令并添加了一些调整以包含嵌入。但是当我 运行 代码时,我得到了拓扑错误。

这是我收到错误的文件:

const muteSchema = require('@schemas/mute-schema')

module.exports = (client) => {
    const checkMutes = async () => {
        console.log('CHECKING MUTE DATA')

        const now = new Date()

        const conditional = {
            expires: {
                $lt: now
            },
            current: true,
        }
//The error is on this next line, it doesn't like that 'await'
        const results = await muteSchema.find(conditional)

        if (results && results.length) {
            for (const result of results) {
                const { guildId, userId } = result

                const guild = client.guilds.cache.get(guildId)
                const member = (await guild.members.fetch()).get(userId)

                const mutedRole = guild.roles.cache.find((role) => {
                    return role.name === 'Muted'
                })

                member.roles.remove(mutedRole)
            }

            await muteSchema.updateMany(conditional, {
                current: false,
            })
        }

        setTimeout(checkMutes, 1000 * 60 * 10 )
    }
    checkMutes()

    client.on('guildMemberAdd', async (member) => {
        const { guild, id } = member

        const currentMute = await muteSchema.findOne({
            userId: id,
            guildId: guild.id,
            current: true,
        })

        if (currentMute) {
            const role = guild.roles.cache.find((role) => {
                return role.name === 'Muted'
            })

            if (role) {
                member.roles.add(role)
            }
        }
    })
}

这是完成此文件逻辑的另一个文件:link

这里还有架构:link

还有我的 mongo 连接到 mongo 的文件:link

所以我想知道如何解决我的问题,以及对于将来的错误我如何自己解决以及错误的基本含义,因为错误中没有指定我自己的代码的确切行.

每当您遇到上述这些类型的错误时: MongoErrror: Topology is closed,它们指的是与您的 Mongo 数据库的未建立连接,正如您用来连接到 Mongo 数据库的 I could figure out that you never called your connection function in @util/mongo.js file 所指示的。要克服这个问题,您可以在找到结果之前调用该函数并进一步关闭它(良好做法),方法如下:


    const mongo = require("@util/mongo.js"); // reference from WOK source code ( he hasn't added this but filepath would be somewhat this, you can add the filepath to your connection function.
    await mongo().then(async (mongoose) => {
          try {
    const results = await muteSchema.find(conditional)
    ... // Your code to utilise this result 
    } finally {
    mongoose.connection.close()
    }

Work Off Keys 可能忘记提及这是他们许多教程中的常见错误,因此他们有一个未列出的视频 here。大多数情况下,您现在都可以自行修复此错误。