【问题标题】:.findOneAndUpdate() removes all elements in array.findOneAndUpdate() 删除数组中的所有元素
【发布时间】:2020-08-29 12:41:07
【问题描述】:

我正在制作带有警告系统并且效果很好的不和谐,但我想创建editwarn 命令,因此如果有人输入错误,他们可以编辑警告原因。我的代码的问题是它用新的原因替换了 Array 中的所有元素。

您可以在图片上看到,如果我执行命令!editwarn 2 (because i want to edit second warn) not working,它会将数组中的所有元素替换为not working

我的代码

//declare user and userid
let user = message.mentions.users.first()

let split = args.slice(2).join(" ")

Warning.findOneAndUpdate({ userID: user.id },
     { $set: { reason: split } },
     { new: true }).exec((err, data) => {
          if (err) throw err;
          if (!data) {
             return message.reply("User doesn't have any warnings.")
          } else {
              if (args[1] > data.warns) return message.reply("User doesn't have that warning.")
              modLogs.send(embed)
              message.delete();
              return message.reply(`${user.tag} info succesfully edited!`)
         }
});

我不认为这与它有任何关系,但我会写在这里

我的计划

const mongoose = require("mongoose");

const newScheme = mongoose.Schema({
    name: String,
    warns: Number,
    reason: Array,
    userID: String
}, {
    versionKey: false
})

module.exports = mongoose.model('Warning', newScheme)

【问题讨论】:

  • 在你的 { $set: { reason: split } } 中,什么是“split”?
  • let split = args.slice(2).join(" ")

标签: node.js database mongodb mongoose discord.js


【解决方案1】:

看来split 是一个字符串。我不太熟悉模式,但我猜想将字符串“值”写入数组实际上会将 [“值”] 写入文档,这就是正在发生的事情。您需要更新要更改的元素,而不是覆盖整个数组。

要更新数组中的第三个元素,请使用“reason.2”。像这样:

let split = args.slice(2).join(" ")

let indexToUpdate = 2

Warning.findOneAndUpdate({ userID: user.id },
     { $set: { ["reason." + indexToUpdate]: split } },
 ...

【讨论】:

  • 工作感谢!我会将您的答案编辑为 100% 正确。 indexToUpdate = 2 至少在我的情况下应该是 let indexToUpdate = args[1] - 2。再次感谢!
【解决方案2】:

{$set: {reason: split}} 的更新对象中,您正在用新的输入值覆盖现有数组。您应该尝试做的是搜索数组并使用新输入更新所需的数组值

【讨论】:

    猜你喜欢
    • 2013-05-16
    • 2017-03-25
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多