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

Time:05-20

I am currently having a problem about my signup command and when searched about the error I am having which is: MongoServerError: E11000 duplicate key error collection: ShinDB.users index: username_1 dup key: { username: "Shin" }

they always say to drop the collection which I don't want.

what i want is for example i wrote '>signup Shin thisisatest@1234' and if the 'Shin' username is already in the username database it will NOT send the 'MongoServerError' in the console but instead it will send an error 'That username already exist' in the channel which the user send it to.

Signup Command:

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!'})
                }

            })

        }
    }
}

User 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)

Full Error:

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

My Database Current Collections:

Collections Picture

i hope i have explained it very well, any help would be really appreciated. thanks.

CodePudding user response:

To fix your bot instance shutting down use the following:

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

Along with that. Whatever you're doing with your MongoDB code is very "jank". The following will likely fix it.

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

Let me know if you have any questions

  • Related