What is the best way to delete a nested document within an array in MongoDB by referencing its _id?

I am trying to remove a nested object from an array of objects called createdEvents if the createdEventId matches the id I pass to it.

This is the JavaScript query I am using:

db.collection("users").updateOne({ _id: userId }, { $pull: { createdEvents: { "createdEvents.createdEventId": eventId } } })

I have also attempted the following with no success

 const deleteUserCreatedEvent = await db.collection("users").updateOne({ _id: userId }, { $pull: { createdEvents: { "createdEventId": eventId } } })

This is how my document is structured:

{
  "_id": {
    "$oid": "63669a7fadb92eac2df57fc9"
  },
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef988e8496988e96818ad7dfaf88828e8683c18c8082">[email protected]</a>",
  "emailVerified": {
    "$date": {
      "$numberLong": "1667668607915"
    }
  },
  "createdEvents": [
    {
      "createdEventName": "pushevent",
      "createdEventDate": {
        "$date": {
          "$numberLong": "1667913330000"
        }
      },
      "createdEventDescription": "It's gonnam be a good one",
      "createdEventWeights": [],
      "createdEventId": {
        "$oid": "6368222391d6001d3d2986e2"
      }
    }
  ]
}

Although the code returns true indicating success, the document remains unchanged in the database after running the query.

Answer №1

Ensure that you utilize the new ObjectId(theIdString) function before executing the subsequent query:

updateOne({_id: new ObjectId(userId)}, {$pull: {createdEvents:{createdEventId:new ObjectId(eventId) }}})

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

Using the find() function in Mongo does not effectively work alongside multer in order to display a comprehensive

Recently, I created a basic CRUD API using multer/gridfs to store image files. While it successfully handles tasks like adding, deleting, and finding images by their names, there seems to be a problem with listing all the uploaded files using the find() me ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

Issue with dynamic code detected by Sys.Application.add_init

I am facing a challenge with an older application that I recently took over ownership of. My efforts to successfully run it have been partially fruitful, as I am encountering some strange behavior that seems to be related to Internet Explorer 11. Interesti ...

Local Storage State Persistence Issue with React Checkbox Component

I am currently working on a React component that features a checkbox. My goal is to have the checkbox toggle between on and off states and save this state in local storage so that even when navigating to another page, the toggle will remain in its previous ...

Transform an object into an array using JavaScript with the help of Lodash, Azure Functions, and Azure Logic Apps

To achieve the desired result of extracting JSON from a proprietary content management system, transforming it into a CSV, and depositing that CSV in an Office 365 shared drive, a combination of Azure Function and Azure Logic App is utilized. The Node/Java ...

Advanced Techniques: Leveraging Master Layouts, Partial Rendering, and JavaScript Function

Trying to understand the sequence of events when a master page, partials, and JavaScript code are involved. Imagine having a Master page with scripts: <%@ Master Language="C#" ... %> <head> <asp:ContentPlaceHolder ID="HeadContent" run ...

Performing a MongoDB (Pymongo) query with the $in operator while utilizing ObjectId

I have a list of unique identifiers and I need to perform a query on a collection using this list. The field I'm filtering is id_, which is stored as an ObjectID. For example: list = ['efgh','ijkl','mnop'] I want to re ...

add the closing </div> tag using jquery only

Having a slight issue here, it seems that jQuery is being overly clever. Within my HTML code, I am attempting to insert this string into a div container: </div><div class="something"> You'll notice that the closing tag comes first, foll ...

Utilizing a background image property within a styled component - Exploring with Typescript and Next.js

How do I implement a `backgroung-image` passed as a `prop` in a styled component on a Typescript/Next.js project? I attempted it in styled.ts type Props = { img?: string } export const Wrapper = styled.div<Props>` width: 300px; height: 300px; ...

Utilizing regular expressions in Javascript to retrieve multiple instances

This paragraph contains a specific string txt = "Local residents o1__have called g__in o22__with reports..."; that requires extracting numbers between each occurrence of o and __ If we use the following regex: txt.match(/o([0-9]+)__/g); We will obtain ...

Sending an error code that is specific to the situation to the AJAX error function

I am attempting to send a custom error code to the client-side for ajax error handling. On the server side: $response = array(); if ( empty($post['parent_id']) ) { $response = array('error' => true, 'status_code' => ...

Phantom-node failing to return the value from the page.evaluate function

My goal is to extract a specific element from a webpage and save it as an image locally. Here is the node.js code I am using with phantom-node: var phantom = require('phantom'); phantom.create().then(function(ph) { ph.createPage().then(funct ...

The NGRX state in Angular is not being properly saved by the local storage

Currently, I am utilizing NGRX for state management within my Angular application. While NGRX is functioning correctly, I have encountered an issue with using local storage to persist the NGRX state. Upon refreshing the browser, the NGRX data reverts back ...

Can you explain the distinction between mongoose.save() and passport-local-mongoose.register()?

Can you explain the distinction between using mongoose's .save() and passport-local-mongoose's .register() functions? Why is it that passport-local-mongoose's .register() function only requires a username and password? Wouldn't it be b ...

jQuery Modal activated only once upon clicking

Recently, I've been experiencing a frustrating issue that's giving me a splitting headache. Despite scouring this forum for answers, my problem persists. Here's the situation: I have a button that triggers modals. Upon first click after refr ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Uh oh! AngularJS just threw an error: Uncaught TypeError - angular.service is not a function. It happened in taskService.js

I've run into some issues with AngularJS, even though I have imported all the necessary libraries. Specifically, I am encountering the following errors: Uncaught TypeError: angular.service is not a function at taskService.js:2 taskFactory. ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...

The Intersection Observer fails to function properly with images

I recently discovered that images require different intersection observer code than text in order to function properly. After making the necessary changes to the code, my intersection observer is behaving quite oddly. As I scroll down, the image stays hidd ...

Utilize a function from another component

Is there a way to access a function inside main.js using a button in navbar.js to open a drawer that is located within the main.js component? Do I need to utilize Redux for this task? <Navbar /> <main /> navbar.js <Button type="default ...