0

I need to delete an array element using its index with mongoose, atm what I'm doing is splice the array and then update the database using $set, isn't there a more direct way to do this?

vcs = vcs.splice(vcIndex, 1);
await client.guildSchema.updateOne({guildID: oldState.guild.id}, {'$set':{'vcs':vcs}})
Giuliopime
  • 707
  • 4
  • 21
  • if it's the first or last element you can use $pop – user120242 Jul 20 '20 at 13:48
  • I need to use the index – Giuliopime Jul 20 '20 at 13:50
  • 1
    Does this answer your question? [In mongoDb, how do you remove an array element by its index?](https://stackoverflow.com/questions/4588303/in-mongodb-how-do-you-remove-an-array-element-by-its-index) – user120242 Jul 20 '20 at 13:53
  • This says that it's not possible but 9 years have gone by, I wonder if there is a solution now – Giuliopime Jul 20 '20 at 14:04
  • 1
    There are many alternatives and solutions on that page, and comments explaining the inherent problem with trying to do what you're trying to do (problems with atomicity). The linked issue tracker also explains the 9 years, and the official project's response and suggested solution. – user120242 Jul 20 '20 at 14:08
  • Ok so I guess that is not possible, I'll look over the other page and see what I can find, thanks. – Giuliopime Jul 20 '20 at 14:11
  • 1
    Just to point something out: they have left it like that most likely to discourage the mindset and make sure you know what you're doing, so you don't think of it as `.remove(index)`. You could easily create your own function that returns an object representing a `remove(index)` query if you really want the convenient syntax (sugar). But I would agree with the choice of not making it a built-in feature, so as not to encourage this kind of usage without the user being well aware of what they are doing to avoid race conditions or anti-performance patterns. – user120242 Jul 20 '20 at 14:18

0 Answers0