txshiro
txshiro

Reputation: 218

.findOneAndUpdate() removes all elements in array

I'm making discord which has warning system and that works great, but I want to create editwarn command so if someone mistype they can edit the warn reason. The problem with my code is that it replaces all elements in Array with the new reason.

You can see on the pictures that if I do the command !editwarn 2 (because i want to edit second warn) not working it replaces all of the elements in array with not working.

enter image description here enter image description here

my code

//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!`)
         }
});

I don't think this has anything to do with it but I will write it here

My scheme

const mongoose = require("mongoose");

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

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

Upvotes: 0

Views: 205

Answers (2)

Viktor W
Viktor W

Reputation: 1149

It seems that split is a string. I'm not really familiar with schemas, but I would guess that writing a string "value" to an array actually writes ["value"] to the document, and that this is what is happening. You need to update the element you wish to change, not overwrite the entire array.

To update the 3rd element in the array, use "reason.2". Like so:

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

let indexToUpdate = 2

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

Upvotes: 1

Inside your update object which is {$set: {reason: split}}, your are overwriting your existing array with new input value. What you should try doing is to search through the array and update the desired array value with the new input

Upvotes: 0

Related Questions