首页 > 解决方案 > Mongoose.js 没有从数组中删除对象

问题描述

我将 Mongoose 与我的 Discord 机器人一起使用,并且我正在制作可以从任何提到的用户中删除违规行为的功能。

违规行为被保存在Array

但是,当尝试从数组中删除对象时,什么也没有发生,也没有错误。

这是我的代码

定义foundCase (返回此对象)

{
  type: 'warn',
  caseNum: 6,
  userID: '300816697282002946',
  responsibleModerator: '300816697282002946',
  reason: 'playing minecraft',
  date: 1592678689923
}

我的代码

let foundCase = message.guild.data.infractions.find(c => {
                        return c.userID === calledMember.user.id && c.caseNum === Number(caseNum);
                    })

                    if (!foundCase)
                        return message.channel.send(`There were no cases found with that ID to remove from this user. Please ensure the case number is correct, and the user you are mentioning is the right user.`)



                    console.log(foundCase)
                    await client.guildData.updateOne( { guildData: message.guild.id }, { $pull: { infractions: foundCase }})
                    message.channel.send(`I have successfully deleted case number \`${caseNum}\`, and removed the infraction from the user. The change will reflect in any reports within 5 mins.`)
                

然而,什么也没有发生。违规根本没有被删除,仍然在数组中。

有人有什么建议吗?

标签: javascriptmongodbmongoosediscord.js

解决方案


如果没有 Id 匹配,则可能是您的 foundCase 返回并为空对象的情况,因此为了安全起见,将此行更改if (!foundCase)为此if(foundCase.userId=="undefined")

你也可以试试这个

client.guildData.updateOne( { guildData: message.guild.id }, { $pull: { infractions: "foundCase"}})

或这个

client.guildData.updateOne( { guildData: message.guild.id }, { $pull:{infractions: { $in: [ "foundCase"] }}})

推荐阅读