Discord.js v14中MongoDB报Cannot read properties of undefined (reading 'push')错误修复
问题排查与修复
错误原因分析
报错Cannot read properties of undefined (reading 'push')说明你在对一个undefined值调用push方法,结合代码主要存在两处问题:
- 数据库字段类型错误:创建新黑名单文档时,
Words字段被赋值为单个字符串而非数组。后续查询该文档时,data.Words是字符串类型,不存在push方法,调用data.Words.push(word)会直接报错。 - Collection取值未做兜底:
blacklistedWords.get(interaction.guild.id)如果未获取到对应数据会返回undefined,直接调用push也会触发该错误。
修复步骤
1. 修正数据库初始化的字段类型
创建新文档时,将Words设置为包含单个元素的数组:
new Schema({ Guild: interaction.guild.id, Words: [word] // 改为数组,而非单个字符串 }).save();
2. 对Collection的取值做兜底处理
在调用push前先判断是否存在对应数据,不存在则初始化空数组:
// 替换原blacklistedWords.get(...).push(word)代码 const currentBlacklist = blacklistedWords.get(interaction.guild.id) || []; currentBlacklist.push(word); blacklistedWords.set(interaction.guild.id, currentBlacklist);
3. 异步操作添加await(可选但推荐)
data.save()是异步操作,添加await确保数据保存完成后再回复用户,避免数据不一致:
await data.save();
修改后的完整代码
const { Client, CommandInteraction, EmbedBuilder, Permissions, ApplicationCommandType } = require("discord.js"); const { Formatters } = require('discord.js'); const blacklistedWords = require("../../Collection/index.js"); const Schema = require('../../models/blacklist.js') module.exports = { name: "blacklist_add", description: "add a word to blacklist so that the members of the server cannot use the word", userPerms: ['Administrator'], type: ApplicationCommandType.ChatInput, options: [{ name: 'word', description: 'word to be added to the blacklist', type: 3, required: true }], /** * * @param {Client} client * @param {CommandInteraction} interaction * @param {String[]} args */ run: async (client, interaction, args) => { const sword = interaction.options.getString('word'); console.log(sword) const word = sword.toLowerCase(); const guild = { Guild: interaction.guild.id } Schema.findOne(guild, async(err, data) => { if(data) { if(data.Words.includes(word)) return interaction.followUp(`The word already exists in the blacklist did you mean to remove it if so please use /blacklist-remove ${word} to remove the word from blacklist`) data.Words.push(word) await data.save(); // 修复Collection的push操作 const currentBlacklist = blacklistedWords.get(interaction.guild.id) || []; currentBlacklist.push(word); blacklistedWords.set(interaction.guild.id, currentBlacklist); }else { await new Schema({ Guild: interaction.guild.id, Words: [word] // 修正为数组 }).save(); blacklistedWords.set(interaction.guild.id, [ word ]) } const embed = new EmbedBuilder() .setTitle('<:donetick:951395881607893062> Blacklist system') .setColor('GREEN') .setDescription('Word added- A new word has been added to the blacklist') .addField('Word', `${word}`, false) .addField('How do I remove the word from the blacklist?', `/blacklist-remove ${word}`, false) interaction.reply({ embeds: [embed] }) }); }, };
内容的提问来源于stack exchange,提问作者Mohammad Zohaib Ur Rahman
相关产品推荐
相关产品推荐

