MongoError:E11000 重复键错误集合(欢迎和经济代码)

时间:2021-06-13 17:29:06

标签: mongodb discord.js

所以我不断收到有关我的不和谐 js 机器人的上述错误。我知道这是因为我的经济代码与我尝试制作欢迎代码发生冲突,但由于我的基础知识不存在,我希望社区中的某个人可以帮助解决这个问题。

第一行代码是我的公会代码(从事件下拉),第一行是guildMemberAdd.js,代码是:


    const profileModel = require('../../models/profileSchema');
    
    module.exports = async(client, discord, member) => {
        let profile = await profileModel.create({
            userID: member.id,
            serverID: member.guild.id,
            coins: 1000,
            bank: 0,
        });
        profile.save();
    };

公会文件中的下一个文件是 message.js,其中的代码是:


    require("dotenv").config();
    const profileModel = require("../../models/profileSchema");
    const cooldowns = new Map();
    
    module.exports = async (Discord, client, message) => {
      const prefix = process.env.PREFIX;
    
      if (!message.content.startsWith(prefix) || message.author.bot) return;
    
      let profileData;
      try {
        profileData = await profileModel.findOne({ userID: message.author.id });
        if (!profileData) {
          let profile = await profileModel.create({
            userID: message.author.id,
            serverID: message.guild.id,
            coins: 1000,
            bank: 0,
          });
          profile.save();
        }
      } catch (err) {
        console.log(err);
      }
    
      
      const args = message.content.slice(prefix.length).split(/ +/);
      const cmd = args.shift().toLowerCase();
    
      const command = client.commands.get(cmd) || client.commands.find((a) => a.aliases && a.aliases.includes(cmd));
      if (!command) return message.channel.send("This command does not exist!");
    
      if (!cooldowns.has(command.name)) {
        cooldowns.set(command.name, new Discord.Collection());
      }
    
      const current_time = Date.now();
      const time_stamps = cooldowns.get(command.name);
      const cooldown_amount = (command.cooldown) * 1000;
    
      //If time_stamps has a key with the author's id then check the expiration time to send a message to a user.
      if (time_stamps.has(message.author.id)) {
        const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
    
        if (current_time < expiration_time) {
          const time_left = (expiration_time - current_time) / 1000;
    
          return message.reply(`Please wait ${time_left.toFixed(1)} more seconds before using ${command.name}`);
        }
      }
    
      //If the author's id is not in time_stamps then add them with the current time.
      time_stamps.set(message.author.id, current_time);
      //Delete the user's id once the cooldown is over.
      setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);
    
      try {
        command.execute(message, args, cmd, client, Discord, profileData);
      } catch (err) {
        message.reply("There was an error trying to execute this command!");
        console.log(err);
      }
    };

接下来是包含welcome.js文件的features文件夹,其中的代码是:


    // "welcome.js" file within the "features" folder
    module.exports = client => {
        client.on('guildMemberAdd', member => {
          console.log(member.user.tag)
        })
      }

下一个文件夹是handlers文件夹,里面有2个文件,第一个是command_handler.js,里面的代码是:


    const fs = require('fs');
    
    module.exports = (client, Discord) =>{
        const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
    
        for(const file of command_files){
            const command = require(`../commands/${file}`);
            if(command.name){
                client.commands.set(command.name, command);
            } else {
                continue;
            }
        }
    }

第二个文件是 event_handler.js,其中的代码是:


    const fs = require('fs');
    
    module.exports = (client, Discord) =>{
        const load_dir = (dirs) =>{
            const event_files = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith('.js'));
    
            for(const file of event_files){
                const event = require(`../events/${dirs}/${file}`);
                const event_name = file.split('.')[0];
                client.on(event_name, event.bind(null, Discord, client))
            }
        }
    
        ['client', 'guild'].forEach(e => load_dir(e));
    }

最后一个文件夹是models文件夹,其中包含profileSchema(经济)和welcome-channel.js文件。 profileSchema 代码是:


    //PROFILE SCHEMA--------------------------------------------------------
    const mongoose = require("mongoose");
    
    const profileSchema = new mongoose.Schema({
      userID: { type: String, require: true, unique: true },
      serverID: { type: String, require: true },
      coins: { type: Number, default: 1000 },
      bank: { type: Number },
    });
    
    const model = mongoose.model("ProfileModels", profileSchema);
    
    module.exports = model;

并且welcome-channel.js 代码是:


    // "welcome-channel.js" file within the "models" folder
    const mongoose = require('mongoose')
    // We are using this multiple times so define
    // it in an object to clean up our code
    const reqString = {
      type: String,
      required: true,
    }
    const welcomeSchema = new mongoose.Schema({
      _id: reqString, // Guild ID
      channelId: reqString,
    })
    module.exports = mongoose.model('welcome-channel-tutorial', welcomeSchema)

设置欢迎频道的直接命令是setwelcome.js,代码是:


    // "setwelcome.js" file within the "commands" folder
    const welcomeChannelSchema = require('../models/welcome-channel')
    const cache = new Map()
    // An async function to load the data
    const loadData = async () => {
      // Get all stored channel IDs
      const results = await welcomeChannelSchema.find({})
      // Loop through them all and set them in our map
      for (const result of results) {
        cache.set(result._id, result.channelId)
      }
    }
    // Invoke this function when the bot starts up
    loadData()
    module.exports = {
        name: "setwelcome",
      requiredPermissions: ['ADMINISTRATOR'],
      execute: async ( message, args, cmd, client, discord, profileData ) => {
        // Destructure the guild and channel properties from the message object
        const { guild, channel } = message
        // Use find one and update to either update or insert the
        // data depending on if it exists already
        await welcomeChannelSchema.findOneAndUpdate(
          {
            _id: guild.id,
          },
          {
            _id: guild.id,
            channelId: channel.id,
          },
          {
            upsert: true,
          }
        )
        // Store the information in the cache
        cache.set(guild.id, channel.id)
        message.reply('Welcome channel set!')
      },
    }
    module.exports.getChannelId = (guildId) => {
      return cache.get(guildId)
    }

我收到错误的那一刻是当我执行命令 simjoin.js 时,它的代码是:


    // "simjoin.js" file within the "commands" folder
    module.exports = {
        name: "simjoin",
        requiredPermissions: ['ADMINISTRATOR'],
        execute: ( message, args, text, client ) => {
          client.emit('guildMemberAdd', message.member)
        },
      }

请注意,欢迎代码尚未完成,但从此刻起它应该仍然可以工作,但由于重复键错误,这不是我需要您帮助的原因! >

0 个答案:

没有答案