使错误在通道而不是控制台中发送,这样程序就不会停止 运行

make the error send in channel instead of the console so the program wont stop running

我目前的注册命令有问题,当搜索到我遇到的错误时: MongoServerError: E11000 duplicate key error collection: ShinDB.users index: username_1 dup key: { username: "Shin" }

他们总是说放弃我不想要的 collection。

我想要的是,例如我写了 '>signup Shin thisisatest@1234',如果 'Shin' 用户名已经在用户名数据库中,它不会在控制台中发送 'MongoServerError',而是会在用户将其发送到的频道中发送错误 'That username already exist'

注册命令:

var strongRegex = new RegExp("^(?=.{14,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{10,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{8,}).*", "g");
var specialChar = /[`!@#$%^&*()_+\-=\[\]{};':"\|,.<>\/?~]/;
const User = require('../../Database/models/user')

module.exports = {
    name: "signup",
    description: "Signup for an Economy Account",
    usage: ">signup",
    aliases: [],
    run: async (client, message, args) => {
        //message is inguild
        if (message.inGuild()) {
            return message.reply({ content: `This command can only be used in <@${client.user.id}> DM.\n\`\`Usage: >signup <username> <password>\`\`\n\`\`Note: Your Economy Account is Safe\`\`` })
        }

        //message is in DM
        if (message.channel.type === 'DM') {
            
            // USERNAME
            const userargs = args[0]
            const pass = args[1]

            if (!userargs) {
                return message.reply({ content: '**Please provide a username for your Economy Account!\n``Correct Usage: >signup <username> <password>``**' })
            }

            const userToLow = userargs.toLowerCase()
            const user = userToLow.charAt(0).toUpperCase() + userToLow.substring(1, userToLow.length)
            
            if (user.length < 3) return message.reply({ content: '**[__Too Short__]** **Your Username must have atleast 3 Characters**' })
            if (user.length > 7) return message.reply({ content: '**[__Too Long__]** **You Username must only have 7 Characters**' })
            if (specialChar.test(user)) {
                return message.reply({ content: '**Username\'s must not have any Special Characters**' })
            }

            // PASSWORD
            let str
            let med
            let weak
            if (strongRegex.test(pass)) {
                str = 'Strong'
            }
            if (mediumRegex.test(pass)) {
                med = 'Medium'
            }
            if (!strongRegex.test(pass) && !mediumRegex.test(pass)) {
                weak = 'Weak'
            }

            if (!pass) return message.reply({ content: '**Please provide a password for your Economy Account!**' })
            if (pass.length < 8) return message.reply({ content: '**[__Too Short__]** **Your Password must have atleast 8 Characters**' })

            // CREATING THE ACCOUNT
            User.findOne({ createdBy: message.author.id }, async (err, data) => {
                if (data) {
                    return message.reply({ content: `**You already have made an Account and the Username of the Account that you made is: \`\`${data.username}\`\`\n\`\`Note: if you forget your password you can just run the command >recoveraccount\`\`**` })
                } else if (err) {
                    return message.reply({ content: 'That username already exist' })
                } else {
                    new User({
                        loggedInOn: "0",
                        createdBy: message.author.id,
                        isLoggedIn: false,
                        username: user,
                        password: pass,
                    }).save()
                    return message.reply({ content: 'You have successfuly made an Economy Account!'})
                }

            })

        }
    }
}

用户Schema/Model:

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    loggedInOn: String,
    createdBy: String,
    isLoggedIn: Boolean,
    username: {
        type: String,
        unique: true
    },
    password: String
})

module.exports = mongoose.model('Users', userSchema)

完整错误:

                return callback(new error_1.MongoServerError(res.writeErrors[0]));
                                ^

MongoServerError: E11000 duplicate key error collection: ShinDB.users index: username_1 dup key: { username: "Shin" }
    at C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\operations\insert.js:53:33
    at C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection_pool.js:273:25
    at handleOperationResult (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\sdam\server.js:327:20)
    at Connection.onMessage (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:215:9)
    at MessageStream.<anonymous> (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:63:60)
    at MessageStream.emit (node:events:527:28)
    at processIncomingData (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
    at MessageStream._write (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10) {
  index: 0,
  code: 11000,
  keyPattern: { username: 1 },
  keyValue: { username: 'Shin' },
  [Symbol(errorLabels)]: Set(0) {}
}

我的数据库当前 Collections:

Collections Picture

我希望我已经解释得很好,任何帮助将不胜感激。谢谢。

要修复您的机器人实例关闭问题,请使用以下方法:

client.on('error', (error) => {
console.error(error)
// You can also put your "error message" create here
})

随之而来。无论您使用 MongoDB 代码做什么,都非常“卡顿”。以下可能会修复它。

User.findOne({ createdBy: message.author.id }).then((data) => {
  if (data) {
    return message.reply({
      content: `**You already have made an Account and the Username of the Account that you made is: \`\`${data.username}\`\`\n\`\`Note: if you forget your password you can just run the command >recoveraccount\`\`**`,
    });
  } else if (!data) {
    User.findOne({ username: user }).then((findUsername) => {
      if (findUsername) {
        return message.reply('There is already an account with that username!')
      } else {
        new User({
          loggedInOn: '0',
          createdBy: message.author.id,
          isLoggedIn: false,
          username: user,
          password: pass,
        }).save();
        return message.reply({ content: 'You have successfuly made an Economy Account!' });
      }
    });
  }
});

如果您有任何问题,请告诉我