How can I alter an object within an array of a document using a query in Mongoose?

I am working with a data structure:


{
  field: 1, 
  field: 3,
  field: [
    { _id: xxx , subfield: 1 },
    { _id: xxx , subfield: 1 },
  ] 
}

My task is to update a specific element within the array.

Currently, my method involves removing the old object and inserting a new one, but this causes a change in the order of the elements.

This is how I am currently implementing it:

            const product = await ProductModel.findOne({ _id: productID });
            const price = product.prices.find( (price: any) => price._id == id );

            if(!price) {
                throw {
                    type: 'ProductPriceError',
                    code: 404,
                    message: `Coundn't find price with provided ID: ${id}`,
                    success: false,
                }
            }

            product.prices.pull({ _id: id })
            product.prices.push(Object.assign(price, payload))
            await product.save()

I am exploring if there might be a more atomic way to achieve this. The current approach doesn't appear to be secure.

Answer №1

A solution to updating a specific object within an array involves locating it first. To achieve this, consider using the positional '$' operator which can be found here.

When working with mongoose, your code snippet might look something like this:

 await ProductModel.updateOne(
      { _id: productID, 'prices._id': id },//Locating Product with a particular price
      { $set: { 'prices.$.subField': subFieldValue } },
 );

Note the use of the '$' symbol in prices.$.subField. This enables MongoDB to update only the element at the identified index.

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

Troubleshooting issues with Angular 8 component testing using karma leads to failure

As I begin testing my component, my first goal is to verify that the ngOnInit function correctly calls the required services. agreement.component.ts: constructor(private agreementService: AgreementService, private operatorService: Operato ...

Modify the CSS properties of the asp:AutoCompleteExtender using JavaScript

Is there a way to dynamically change the CompletionListItemCssClass attribute of an asp:AutoCompleteExtender using JavaScript every time the index of a combobox is changed? Here is the code snippet: ajaxtoolkit: <asp:AutoCompleteExtender ID="autocom" C ...

Different Ways to Customize Button Click Events in Angular 9 Based on Specific Situations

In my Angular 9 web application development, I frequently need to integrate Bootstrap Modals like the example below: <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="do ...

How can I attach an existing event to a dynamically loaded element using AJAX?

In the main page of my website, there is a button: <button class="test">test</button> Additionally, I have included the following script in my code: $('.test').on('click',function(){ alert("YOU CLICKED ME"); } ...

Refresh the Document Object Model (DOM) and transmit the present time

I am having an issue with sending the actual current time when a button is clicked. Instead of getting the current time, I am receiving the time when the page initially loaded. This button is used to submit a form on Google Sheets using an API. This is th ...

Tips for being patient while waiting for a function to return a value

I'm working on a React class and I'm facing an issue. The problem is that the variable isTokenActive is returning undefined, and I suspect it's because I need to wait for the function checkIfRefreshTokenWorking to return a value. componentD ...

How can I utilize Mongoose to perform a search using distinct search criteria that do not overlap?

Can someone assist me with utilizing Model.find() in Mongoose? I’ve recently included a boolean field called isPrivate to a data model, allowing users to determine if they want their entries to be publicly visible or restricted to themselves. Below is t ...

After the update, MongoDB fails to start

After encountering some naming errors, I decided to upgrade my MongoDB server from version 3.2 to 3.6. The 3.2 version was working perfectly fine for me until then. I downloaded MongoDB 3.6 from https://www.mongodb.com/download-center/community, installed ...

Struggling to adjust the quantity of items in a basic shopping cart when adding multiples of the same item

Hello there! I'm currently working on a project where I need to increase the quantity of each item added to the cart if it's already in there. This is actually my first time posting, so any tips on asking better questions would be greatly appreci ...

Removing all table rows except one in Jquery

I currently have this code in my view: <script> $(document).ready(function() { $("#add_instruction").click(function(){ $("#instructions").append("<tr><td></td><td><input type='text' name='rec ...

Magnific Popup displaying only the initial item

As someone new to using jQuery and Magnific Popup, I am working on a grid of images. When an image is clicked, I want Magnific Popup to display a specific div containing information relevant to that particular image. <div class="grid"> <div c ...

Best Practices in D3 Visualization Using Static Data Architecture

My current project involves a D3 data visualization that creates a force layout graph using data from a JSON file containing 500 objects. The application is developed using node and express. I'm contemplating whether it's advisable to store this ...

Display the element when it becomes visible in the user's viewport as they

I've been struggling to implement a feature where an element is shown on scroll when it's in the viewport and hidden when it's not. However, despite my efforts, I haven't been able to get it working properly. Here's what I have so ...

Navigating with Angular 1.5 Component router in conjunction with Express.js

I'm currently working on an Express application and I am trying to capture all routes to redirect users to /public/app/index.html: app.all('/*', function (req, res, next) { // Let's just serve the index.html for other files to enab ...

Elevate the value of a particular element's variable through the execution of a function

By using a for loop, I was able to generate a variable number of divs that change their background color individually when hovered over with the mouse. Now, I want to implement a function that will decrease the brightness of each div by 10% every time it i ...

Error: Unable to locate Mongoengine.django

Python ver=3.4 Django ver=1.9.2 Currently, I am in the process of integrating MongoDB with my Django project that is running on version 1.9.2. To achieve this, I have successfully installed mongoengine in my virtual environment and made the necessary con ...

Is there a way to implement a @click event on a Vuetify expansion panel?

Whenever I use <a>, the design of the <v-btn> expansion panel breaks. How can I incorporate the click event in this situation? I attempted to utilize filters, watch, and computed, but it didn't work. Here's my code: <v-card xs1 ...

The 'id' property cannot be accessed because the data has not been retrieved successfully

After loading my App, the data from Firebase is fetched in componentDidMount. I am currently passing postComments={comments} as a prop. However, before this happens, my app crashes with Cannot read property 'id' of undefined on line const c ...

Is it possible to retrieve a variable from code.gs and pass it to my html file?

I had originally set up an automated email system to trigger once a certain condition was met, which I successfully implemented. However, I now want to enhance the email by including a more structured format and embedding an image from Google Drive. While ...

The functionality to remove table rows when checkboxes are selected is not functioning as expected in an Angular 7 application

My table contains data generated from a loop. When I click the edit button, additional buttons and textboxes are enabled. If multiple checkboxes are checked, the add buttons become disabled. However, if all checkboxes except one are unchecked, the add bu ...