javascript - 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.`)
然而,什么也没有发生。违规根本没有被删除,仍然在数组中。
有人有什么建议吗?
解决方案
如果没有 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"] }}})
推荐阅读
- python - 在 def python 中传递类变量
- ios - 检测设备是否可以传输 iBeacons - 核心蓝牙
- openid - OpenId 3 到 OpenId 4 多个颁发者名称
- javascript - Azure AD 身份验证 Ember JS v3.15
- pytorch - 如何正确使用 Pytorch 的 View 功能?
- php - 使用适用于 QuickBooks 的 Consolibyte PHP SDK,如何识别哪个客户端正在从 Web 连接器发送调用?
- swift - 解码错误:typeMismatch - 预期解码字典
但找到了一个字符串/数据 - android - 在启动 Intent 时尝试在空对象引用上调用虚拟方法
- firebase - Firebase 命令在终端中引发错误
- rust - 如何使用 RefCell 在 Deref 实现中指定 Target 类型的生命周期?