Home > Back-end >  Why does using slice in MongoDB updateOne does not delete an item from an array but only replaces it
Why does using slice in MongoDB updateOne does not delete an item from an array but only replaces it

Time:03-06

so there the array coursesFollowing and inside it objects like this for example:

objInside = {
username:"SweetWhite"
courseTitle:"TOMATOaaaaa"
progress:0 
}

and I have a function that finds the right object index in the array of objects of that kind of object and it seems to work in terms of index found and object, however my update request works weirdly when I execute it:

  User.updateOne({username: req.body.username}, {coursesFollowing:{$slice: [removeIndex , 1]}}, function(err,result){
    if(err){return next(err)}
  })

it find the right user to put it in, and also the right field, however it does not remove the object in that removeIndex index, but deletes all the items in the array and puts only one object in, with the array named $slice with the removeIndex as first value and the second value is 1, judging from the data it has not deleted all the other objects but simply replaced them with itself, the operation $slice pushed itself into the array and did not execute I think? I am mildly confused.

anyways, how do I fix this? how do I delete an index of the array without pushing the weird $slice object array thingi?

Thanks!

CodePudding user response:

If you notice your updated document you might realize that you are not updating anything in the array actually using your $slice operator. Instead you are setting a new value for the array. And that is why you see the first element as $slice something and the second as 1.

$slice operator is used with $push and is used to limit the number of elements in the array field finally. The doc doesn't mention removing an array element with this, given its index.

According to this answer there is no simple way to do this.

There is $pull, but it does not work with the given index. It works based on a query condition for the object in the array. So if you are first figuring out the element index and then using it in the update query. You can do that directly.

If you want to use a JS function you can use splice, which does in-place updates. Use the $function

User.updateOne({username: req.body.username}, [{ $set:
{ "coursesFollowing": { $function: { body: function(coursesFollowing) { coursesFollowing.splice(removeIndex, 1); return coursesFollowing; }, args: ["$coursesFollowing"], lang: "js" }} }
  }], function(err,result){
    if(err){return next(err)}
  })
  • Related