Updating a specific item within a subarray in MongoDB using JavaScript may seem daunting at first

Consider the following code snippet:

const previous = await Sports.findById(sportId);

Upon execution, it yields the data below:

{
    _id: "sdsdsds",
    name: "sdsdsds",
    enabled: true,
    markets: [
        {
            enabled: true,
            defId: "LOOKATME",
            name: "sdsdsd",
        },
        {
            enabled: false,
            defId: "dfsdfdsfs",
            name: "sdsdfsdsd",
        },
    ]
}

If I wish to modify the market with a defId of "LOOKATME" and set its enabled status to false using an update function like this:

const modified = await Sports.findByIdAndUpdate(previous, [LOGIC], {new: true});

What steps should be taken to achieve the desired output as shown below?

{
    _id: "sdsdsds",
    name: "sdsdsds",
    enabled: true,
    markets: [
        {
            enabled: false, // this value has been updated
            defId: "LOOKATME",
            name: "sdsdsd",
        },
        {
            enabled: false,
            defId: "dfsdfdsfs",
            name: "sdsdfsdsd",
        },
    ]
}

Answer №1

With the help of the 'await' keyword, we can update a specific document in the Sports collection where the _id matches 'old._id' and the "markets.defId" is equal to "LOOKATME". By setting the "markets.$.enabled" field to false, we are able to successfully update the record.

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

Quirky Behavior of an Array of Objects

const allocation = [ {partner: 3}, {partner: 1}, {partner: 2}, {partner: 0}, {partner: 4} ]; const rightallocation = new Array(5); rightallocation.fill({number: 1}); for (let i = 0; i < allocation.length; i++) { const rightIndex = a ...

What's the deal with $routeProvider in angularJS?

I'm having some trouble with my simple web app that I'm trying to update using route provider. Everything works fine when I click on the list items on the page, but when I refresh the page, I get a 404 error. It seems like it's trying to acc ...

Find the duplicated entries within a sub document array using a MongoDB query

In this scenario, the goal is to identify duplicate records in the sub-document based on certain conditions and output the results as outlined below. Dataset [{ _id: "objectId", name: "product_a", array: [{ _id: "objectId", st ...

Eliminate the option to locate columns in the column selector of the mui DataGridPro

Currently, I am creating a data table for a personal project. Utilizing the DataGridPro element from material ui has been quite satisfying, especially with the column selector feature. However, I wish to eliminate the "find column" section. Is it feasibl ...

Insert a clickable element within an HTML document

I have an idea for a questionnaire that includes questions and an interactive element at the end. At the completion of the questionnaire, there will be a button labeled "display answers" which users can click to reveal the correct responses. For example, ...

Javascript Callback function not working as expected

I'm attempting to include an anonymous callback function in my code. I know it might seem a bit messy. By typing into the intro section, it triggers the animation using the .typed method with specific parameters. What I'm struggling to do is imp ...

Creating a callback function in Twilio using Node.js for the gather action

I am facing a challenge with writing this code in nodejs: <?php // page located at http://example.com/process_gather.php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; echo "<Response><Say> ...

retrieving an array of checkbox values using AngularJS

As a beginner in Angular, I have been struggling to implement a feature where I can add a new income with tags. I have looked at similar questions posted by others but I still can't get it to work. The tags that I need to use are retrieved from a ser ...

Is it possible for PHP to delay its response to an ajax request for an extended period of time?

Creating a chat website where JavaScript communicates with PHP via AJAX, and the PHP waits for the database to update based on user input before responding back sounds like an intriguing project. By using a recall function in AJAX, users can communicate ...

Maximizing the Use of Multiple Conditions for Styling in AngularJS

I have a table where I need to set different colors based on the values in one of the columns. I've successfully managed to set two colors using NgClass, but I'm unsure how to set up three different conditions. <scri ...

Input only the necessary numeral

As someone who is just beginning to learn javascript, I am tasked with creating an input field that allows for the input of 'AND', 123, or (). I attempted using RegExp to achieve this. function requiredletter(inputtxt) { var letters =/&bso ...

Activate the SHIFT key

In the input field for user's firstname, I have restricted all keys to a-z and 0-9 only. This restriction is working well, but I also want to allow the SHIFT key so that users can capitalize letters if needed. Despite trying various solutions, I have ...

Encountered a Soundcloud embedded javascript issue: Unable to execute the 'createPattern' function on 'CanvasRenderingContext2D' due to the canvas width being 0

Encountering an Uncaught InvalidStateError with embedded SoundCloud profiles from (https://w.soundcloud.com/player/widget-6c3640e3.js & https://w.soundcloud.com/player/multi-sounds-0e392418.js) on my website pullup.club hosted on github.io and is open ...

Encountering a problem while trying to locate an item by its unique identifier with M

I'm attempting to search for an object using its ID, but encountering the error message: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id" This is the code I have: var orgID = new mongoose.Types.ObjectId( org_id.organisati ...

Encountering an Uncaught Error: MyModule type lacks the 'ɵmod' property

I am currently working on developing a custom module to store all my UI components. It is essential that this module is compatible with Angular 10 and above. Here is the package.json file for my library: { "name": "myLibModule", &qu ...

Rotation of table columns slider

My goal is to design a table layout with 4 columns, but only display 3 columns at a time. I plan to achieve this by using a div that spans the width of the 3 visible columns and applying overflow: hidden to hide the last column. When the button is clicked, ...

Error: Encountered an unexpected token F while trying to make a POST request using $http.post and Restangular

In our current project, we are utilizing Angular and making API calls with Restangular. Recently, I encountered an error while trying to do a POST request to a specific endpoint. The POST call looked like this: Restangular.one('aaa').post(&apos ...

Preventing Element Reload in Django Using AJAX Across Multiple Templates

NOTE: Updated base.html and refined title UPDATE 2: An example of what I'm referring to is the ticker showing x y z, then transitioning to a, b, c, and so forth. How can I maintain the position of the ticker when navigating pages so that if it's ...

AngularJS: How service query data is perceived as an object and therefore cannot be utilized by Angular

When retrieving data from my PHP server page in the factory service, I encountered two different scenarios: If I call a function that returns an array and then use json_encode($data); at the end, Angular throws a resource misconfiguration error due to ...

Notifying individuals of a file's unavailability using HTML tags

I recently created an API that is designed to deliver files to the frontend. Here is how it looks: <a href="downloadFile.aspx?file=token" download target="_blank"> The file download functionality is working fine. However, the issue arises when the ...