首页 > 解决方案 > 如何在 Discord.js 中成功更新 MongoDB 模式?

问题描述

我一直在尝试创建一个函数,告诉机器人在哪个通道中部署积分系统。我也在使用 MongoDB,这样当我的机器人重新启动时,它会记住积分系统设置在哪个通道中。但是,我得到了诸如 404: Not Found 之类的错误,它甚至不更新架构,因此,我正在寻找可用的解决方案。这是我的代码:

const {
  prefix,
} = require('./config.json')
const Discord = require('discord.js')
var date = new Date().toLocaleString();
module.exports = (client) => {
  const Mongo = require('mongoose')
const LeaderboardSequence = require('./leaderboard.js')
const SLSchema = require('./setLeaderboard.js')
const mongoose = require('mongoose')
mongoose.connect('insert URL here', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false
});
client.on('message', async message => {
if (message.content === `${prefix}setLeaderboardChannel`) {
    // 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 SLSchema.findOneAndUpdate(
      {
        _id: guild.id,
      },
      {
        _id: guild.id,
        channelId: channel.id,
      },
      {
        upsert: true,
      }
    )
    message.reply(`The points channel has been set to <#${channel.id}>!`)
  }
});
client.on('message', async message => {
    const { guild, channel } = message
  const channelId = await SLSchema.find({channelId: channel.id})
      
  if (message.channel.id = channelId) {
      if (message.attachments.size > 0) {
          message.react('')
          message.react('')
        
         
          
      } else {
          message.delete()
      }
  }
  
})
client.on('messageReactionAdd', async (reaction, user) => {
    const { guild, channel } = message
  const channelId = await SLSchema.find({channelId: channel.id})
  if (reaction.partial) await reaction.fetch()
  if (reaction.message.partial) await reaction.message.fetch()
  if (reaction.message.channel.id !== channelId) return;
  if (user.id === client.user.id) return;
  if (reaction.message.author.id === user.id) return reaction.users.remove(user)
  if (reaction.emoji.name === "") {
    await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: 1 } }, { upsert: true , new: true , setDefaultsOnInsert: true })
    
  } else if (reaction.emoji.name === "") {
    await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: -1 } }, { upsert: true , new: true , setDefaultsOnInsert: true})

  }


});
client.on('messageReactionRemove', async (reaction, user) => {
    const { guild, channel } = message
  const channelId = await SLSchema.find({channelId: channel.id})
  if (reaction.partial) await reaction.fetch()
  if (reaction.message.partial) await reaction.message.fetch()
  if (reaction.message.channel.id !== channelId) return;
  if (reaction.message.author.id === user.id) return reaction.users.remove(user)
  if (user.id === client.user.id) return;
  if (reaction.emoji.name === "") {
    await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: -1 } }, { upsert: true , new: true , setDefaultsOnInsert: true })
    } else if (reaction.emoji.name === "") {
    await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: 1 } }, { upsert: true , new: true , setDefaultsOnInsert: true})

  }


});

  client.on('message', async message => {
    if (message.content === `${prefix}leaderboard`) {
      const Users = await LeaderboardSequence.find({guildID: message.guild.id}).sort({ points: -1 })
     
      const embedArray = []
      for (var i = 0; i < Users.length % 10 + 1; i++) {
      const leaderboard = new Discord.MessageEmbed()
      .setTitle(`Here is ${message.guild}'s points leaderboard!`) 
      .setColor("RANDOM")
      .setThumbnail("https://pbs.twimg.com/media/D7ShRPYXoAA-XXB.jpg")
      
      let text = ""
      for (var j = 0; j < 10; j++) {
    if (!Users[ i * 10 + j ]) break;
    text += `${i * 10 + j + 1}. <@${Users[ i * 10 + j ].userid}>: ${Users[ i * 10 + j ].points}\n`
  }
      leaderboard.setDescription(text)
      .setFooter("By (username) and (username), for everyone with the magic of discord.js.")
      .setTimestamp()
      embedArray.push(leaderboard)
      }
      paginate(message, embedArray)
      
    }

  });

  const reactions = ['◀️', '⏸️', '▶️']
async function paginate(message, embeds, options) {
    const pageMsg = await message.channel.send({ embed: embeds[0] })
    await pageMsg.react(reactions[0])
    await pageMsg.react(reactions[1])
    await pageMsg.react(reactions[2])

    let pageIndex = 0;
    let time = 30000;
    const filter = (reaction, user) => {
        return reactions.includes(reaction.emoji.name) && user.id === message.author.id;
    };
    if (options) {
        if (options.time) time = options.time
    }
    const collector = pageMsg.createReactionCollector(filter, { time: time });
    collector.on('collect', (reaction, user) => {
        reaction.users.remove(user)
        if (reaction.emoji.name === '▶️') {
            if (pageIndex < embeds.length-1) {
                pageIndex++
                pageMsg.edit({ embed: embeds[pageIndex] })
            } else {
                pageIndex = 0
                pageMsg.edit({ embed: embeds[pageIndex] })
            }
        } else if (reaction.emoji.name === '⏸️') {
            collector.stop()
        } else if (reaction.emoji.name === '◀️') {
            if (pageIndex > 0) {
                pageIndex--
                pageMsg.edit({ embed: embeds[pageIndex] })
            } else {
                pageIndex = embeds.length-1
                pageMsg.edit({ embed: embeds[pageIndex]})
            }
        }
    });

    collector.on('end', () => pageMsg.reactions.removeAll().catch(err => console.log(err)));
}``
}
在问题中,我没有提到我也在通过 if 语句检查积分通道:

(const { guild, channel } = message

const channelId = await SLSchema.find({channelId: channel.id})) 但这也不起作用。

这是架构:

const { Schema, model } = 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 SLSchema = Schema({
  _id: reqString, // Guild ID
  channelId: reqString,
})
module.exports = model('setLeaderboard', SLSchema)

在第一段代码中,我已经粘贴了整个脚本,以便你们了解我在这里想要完成的事情。

标签: javascriptmongodbdiscord.js

解决方案


推荐阅读