MongoDB 声明模型并删除数据

MongoDB declare model and delete data

我正在尝试创建一个不和谐的机器人,特别是已婚机器人。

在上一题中,我实现了marry命令

现在,使用相同的逻辑,我正在尝试创建一个将从数据库中删除数据的离婚命令。

我做的一切都和那里一样,但我得到一个错误:

OverwriteModelError: Cannot overwrite Marry model once compiled.

如何正确声明模型以便从数据库中查找和删除数据?

const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const mongoose = require("mongoose");

mongoose.connect('mongodb+srv://admon:admin@cluster0.sobzp.mongodb.net/dbname?retryWrites=true&w=majority');

const marrySchema = new mongoose.Schema({
  userID : {
      type : mongoose.SchemaTypes.String,
      required : true
  },

  userPartnerID : {
      type : mongoose.SchemaTypes.String,
      required : true
  }
});

const Marry = mongoose.model('Marry', marrySchema);

module.exports = class DivorceCommand extends Command {
  constructor(client) {
    super(client, {
      name: 'divorce',
      memberName: 'divorce',
      group: 'test',
      description: 'Divorce',
      guildOnly: true,
      args: [
        {
          key: 'userToDivorce',
          prompt: 'Please indicate the member you wish to divorce.',
          type: 'member',
          default: 'isempty',
          wait: 0.0001
        }
      ]
    });
  }

  async run(message, { userToDivorce }) {
    const exists = await Marry.findOne({ userID: message.author.id });
    const divorce = await Marry.findOne({ userID: userToDivorce.id });

    if (userToDivorce == 'isempty') {
        return message.channel.send('Please indicate the member you wish to divorce.')}
    if (exists?.userID !== message.author.id) {
        return message.channel.send('You dont have a soul mate.')}
    if (divorce?.userID !== userToDivorce.id) {
        return message.channel.send('You are not married.')}
    if (exists?.userID === message.author.id && divorce?.userID === userToDivorce.id) {
        const embed = new Discord.MessageEmbed()
      .setDescription(`**Divorce**
    
      ${message.author}, Do you really want to divorce ${userToDivorce}?
  
      `);
    message.channel.send(embed).then(msg => {
      msg.react('✅').then(() => msg.react('❌'))
      setTimeout(() => msg.delete(), 30000)
      setTimeout(() => message.delete(), 30000);
    

      msg.awaitReactions((reaction, user) => user.id == message.author.id 
      && (reaction.emoji.name == '✅' || reaction.emoji.name == '❌'),
        { max: 1, time: 20000, errors: ['time'] })
      .then(collected => {
        const reaction = collected.first();
        if (reaction.emoji.name === '❌') {
            const embed = new Discord.MessageEmbed()
      .setDescription(`It seems that ${message.author} changed my mind.`);
      return message.channel.send(embed)}
    if (reaction.emoji.name === '✅') {
     
      Marry.deleteOne({ userID: message.author.id });
      Marry.deleteOne({ userID: userToDivorce.id });

      const embed = new Discord.MessageEmbed()
      .setDescription(`${message.author} and ${userToDivorce} no longer together.`);
    message.channel.send(embed)
    .catch(() => {
    });
      }
  }).catch(()=>{
    const embed = new Discord.MessageEmbed()
    .setDescription('There was no response after 20 seconds, the offer is no longer valid.');
    message.channel.send(embed)
    .then(message => {
      setTimeout(() => message.delete(), 10000)
    })
    .catch();
  });
}).catch(()=>{
});
}}};

我也试过这个const exists = await mongoose.marries.findOne({ userID: message.author.id });

但是我收到一个错误

An error occurred while running the command: TypeError: Cannot read property 'findOne' of undefined

我认为您已经创建了 Marry 模型并在多个文件中重试或者可能不止一次调用文件。

您可以通过放入 if 条件来阻止

// put following model within condition to avoid error
// const Marry = mongoose.model('Marry', marrySchema);
if (!mongoose.modelNames().includes('Marry')) {
   mongoose.model('Marry', marrySchema);
}
const Marry = mongoose.model('Marry');