Home > Software design >  Remove element in array by its index - mongoose
Remove element in array by its index - mongoose

Time:02-27

I have a mongoose model that looks like this:

 Member: {
  memberId: {
    type: String,
    required: true
  },
  customPlaylists: {
    type: Array,
    default: []
  }
       
         }

customPlaylist's array holds object that look like this:

{ name: 'playlist name', urls: [] } // urls array contains url strings

Is there a way using mongoose's updateOne method to remove a url from the urls array by its index in the array? (I use the member's ID in the filter object)

CodePudding user response:

I'm not sure if there is a straight (1 query) way to do this. But you can try this

<collectionName>.update({}, {$unset : {"urls.<indexNumberHere>" : 1 }}) 
<collectionName>.update({}, {$pull : {"urls" : null}})

There was a ticket to implement this feature and the resolution was Won't Do

CodePudding user response:

As mentioned in the comment here you can do something like this demo

Assuming you have a collection like this

[
  {
    name: "playlist name",
    urls: [
      "url1",
      "url2",
      "url3"
    ]
  }
]

For example if you want to remove the the element at index 1

db.collection.update({},
[
  {
    $set: {
      urls: {
        $concatArrays: [
          {
            $slice: [
              "$urls",
              1  //Put Index 0,1,2...
              
            ]
          },
          {
            $slice: [
              "$urls",
              {
                $add: [
                  1,
                  1  //Put Index 0,1,2...
                  
                ]
              },
              {
                $size: "$urls"
              }
            ]
          }
        ]
      }
    }
  }
])

  • Related