【问题标题】:Mongoose.js not removing object from arrayMongoose.js 没有从数组中删除对象
【发布时间】:2020-10-11 02:45:38
【问题描述】:

我将 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.`)
                

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

有人有什么建议吗?

【问题讨论】:

    标签: javascript mongodb mongoose discord.js


    【解决方案1】:

    如果没有 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"] }}})
    

    【讨论】:

    • 在当时的测试中它是一个完整的对象,所以我知道这不是问题
    • 让我试试这两个,看看会发生什么
    • 不,这些都不起作用。每个结果都相同。什么都没有发生
    猜你喜欢
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2016-11-26
    • 2016-05-19
    • 2011-04-04
    • 2013-03-16
    相关资源
    最近更新 更多