Removing a specific object from a MongoDB array by its unique identifier

I'm currently developing an application that focuses on playlists. Utilizing MongoDB with mongoose, I am storing videos within each playlist using an array structure as demonstrated below:

{
  _id: ObjectId("61ca1d0ddb66b3c5ff93df9c"),
  name: "Playlist A",
  videos: [
    { 
      title: "Video 1",
      url: "www.YouTube.com/video1", 
      startTime: "20",
      endTime: "40", 
      _id: ObjectId("61ca1d1ddb66b3c5ff93e0ba")
    },
    ...
  ]
}

My goal is to remove a video from a playlist based on the _id of the video. Despite researching solutions online, the methods I've attempted have not been successful. This is what my current approach looks like:

Playlist.updateOne(
    { _id: req.params.playlistId },
    { $pull: { videos: { _id: req.params.vidId } } }
)

After executing the provided code and examining the output, I observe the following results (although unsure if this information is pertinent):

{
  acknowledged: true,
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

If any additional details are required, feel free to ask as this marks my first time reaching out for assistance :)

Answer №1

An issue arises with TypeError when req.params.vidId returns a string instead of the expected Type ObjectId that mongoose requires. The simple fix for this is to convert the string (req.params.vidId) into an ObjectId, as shown below:

Playlist.updateOne(
    { _id: req.params.playlistId },
    { $pull: { videos: { _id: mongoose.Types.ObjectId(req.params.vidId) } } }
  )

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When jQuery inserts JavaScript into the DOM, it does not automatically execute the code

UPDATE: I initially used filter(), which was incorrect. I have since switched to find(), but unfortunately the issue persists. This snippet of code functions properly for me: $('#content') .replaceWith($( '<div> <d ...

What is the reason for the checkboxes in vuejs not being rendered with the checked attribute set

When working on an edit form, I encountered a situation where I had multiple options to choose from. These options were fetched via ajax using axios and assigned to the variable permisos in the component. Later, these options are rendered through a v-for l ...

Unable to execute multiple instances of Selenium PhantomJS concurrently

I have encountered an issue while using Selenium's node.js API to run PhantomJS instances against a series of web pages. The code that I have written to perform actions on the pages is functioning correctly, but it appears that only one instance of Se ...

The functionality of the Eslint object-property-newline feature is not functioning as expected

Within my configuration file .eslintrc, I have set "object-property-newline": ["error", { "allowAllPropertiesOnSameLine": true }], and "max-len": "off". However, objects like const something = {a: 5, ffsdfasdasdsddddd: 'asdasdasdddddddddddssssssddddd ...

Guide to implementing mongoose validation with the update() method

I have created a schema with a field that is of type number. I set the minimum value to 0, but after updating it, the value changes to a negative number. Here is my updated schema: let balanceChecker = (v)=>{ if(v<0){ return v=0; }el ...

Tips for delaying the rendering of a directive in AngularJS until the data from a tsv file has been fully loaded

I am trying to integrate d3.js with angularjs to create a line graph using data loaded from a tsv file. However, I am facing an issue where the graph is being rendered before the data is fully loaded. I want the graph to be rendered only after the data has ...

Guide to switching material design icons in Vue JS based on a condition?

I have a button that toggles text, but I want to toggle icons instead. Here's the code I currently have: <b-button size="sm" @click="row.toggleDetails" class="mr-2"> {{ row.detailsShowing ? '-' : '+ ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

Issue with loading controllers in route files [Node.js]

I've encountered an issue while trying to include a user controller into my routes for a node js app. Everything was working fine until suddenly it started throwing an error message. I've thoroughly checked the code for any potential issues but s ...

What is the best way to transfer data between functions?

I'm working on a fun Santa's game to play with my friends. The concept is simple: you enter your name, click a button, and a random name from the list will be displayed as the result. I've encountered a couple of challenges: I can succe ...

Having difficulties getting basic cube rolling animations to function properly in three.js

I am a beginner in the world of THREEJS and currently working on moving a cube using arrow keys. Take a look at this fiddle: https://jsfiddle.net/mauricederegt/y6cw7foj/26/ Everything is functional, I can move the cube with arrow keys and even rotate it c ...

When a model is changed from within a jQuery event, Angular 2 fails to update the view

During the development process, I encountered an issue while creating a custom search panel that displayed search results in a dropdown container. In my controller, I defined the following: export class ProductSearchComponent implements OnInit { publ ...

The use of JQuery repeating fields can cause disruptions to the Bootstrap layout when removing rows

I have been struggling with a form that contains multiple fields that need to be repetitive. My current code is functional, but I'm encountering an issue where clicking on any remove button other than the first one causes the fields in the row to rear ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

Utilizing JavaScript to present JSON data in HTML tables across various sections of a website

Utilizing JScript to retrieve data from a JSON API URL, I have incorporated the data in the JSON file displayed below - containing information on 8 horse races with details like Horse number, Horse name, and their odds. My goal is to create a Jscript code ...

Creating a custom map using React and Leaflet

Can anyone guide me on creating a map using leaflet? I am encountering the following issue. ./src/Map.js Attempted import error: 'Map' is not exported from 'react-leaflet' (imported as 'LeafletMap'). Below is the code I have ...

Automated form with built-in calculations

Whenever a product is selected from the dropdown menu, the price value should be automatically filled in the input field with ID #price. Then, the user can enter the quantity in the input field with ID #quantity, and the total sum of price multiplied by qu ...

The request for POST /users is met with an empty response from the OKTA server, resulting in an

I am currently working on implementing OKTA provisioning with a SCIM endpoint to transfer data from OKTA to my local database. To achieve this, I have set up a SCIM 2.0 Test App (OAuth Bearer Token) with NODE.js and MongoDB as the database. When I assign ...

Is there a way to restrict the number of line breaks in a multiline asp:TextBox control?

Is it possible to restrict a multiline asp:TextBox to only display content on 3 lines using either javascript or C#? ...

Unlocking the properties of an object using strings within a different object

Is it possible to access object properties using a string with another object in JavaScript? var obj = { title : 'spider' } var hero = { spider : 'is a hero' } console.log( hero.spider );//works fine console.log( hero.obj.tit ...