Guide on updating an array within an object's nested array

I am looking for a way to update a field within a nested object in an array using one MongoDB query.

Consider the following schema:

var PlatformPhotoAlbumSchema = new Schema({
  platformAlbumId: String,
  platformPhotoIds: [String]
}, { _id : false });

var SocialProfileSchema = new Schema({
  platformPhotoAlbums: [PlatformPhotoAlbumSchema]
});

For example:

{
platformPhotoAlbums: [
    {
    platformAlbumId: "a",
    platformPhotoIds: ["1","2"]
    },
    {
    platformAlbumId: "b",
    platformPhotoIds: ["3","4"]
    },
    {
    platformAlbumId: "c",
    platformPhotoIds: ["5","6"]
    }
]

}
  1. How can I update the object with platformAlbumId "c" to have platformPhotoIds: ["5","6","7"]?
  2. If no document exists with platformAlbumId as "c", then how can I create a new object with platformAlbumId: "c" and platformPhotoIds: ["5","6","7"] and add it to platformPhotoAlbums?

I want to achieve this using a single mongodb query. Do you have any suggestions on how to accomplish this?

Answer №1

It seems like the task you are trying to achieve can be simplified by considering a different approach for your query.

Your goal is to add a new object to an array of objects structured like this:

{
  platformAlbumId: "c",
  platformPhotoIds: ["5","6"]
}

Prior to adding the new object, you need to remove any existing items in the array that match the criteria for platformAlbumId: "c".

Edit:

Alternatively, you may utilize the findAndModify command with the query based on your platformAlbumId values, update set with your new platformPhotoIds values, and set the upsert boolean to true. For more information, refer to this resource.

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

What is the best way to stop a current action when a new action is initiated?

My current setup involves an action creator that performs a costly calculation and triggers an action when the user inputs data in real-time. The challenge arises when multiple inputs are entered, as I want to avoid running the entire expensive calculati ...

What is the best method for creating numerous Popovers within a single ID?

Is it possible to create multiple popovers with the same ID? <div class="card-text"> <a href="#" id="seelabel" data-toggle="popover" data-trigger="hover" title="Inkscape" data-content= ...

Collection of embedded elements

I'm faced with an array of deeply nested objects. const arr = [ { id: 1, name: "java", answers: { q1: "ex", q2: "ex", q3: "ex", }, }, { id: 2, name: "css", answers: { q1: ...

Looking for assistance with using an array in a for loop with an if-

I'm having trouble with a For loop array. I need to retrieve the data that is opposite of a given function, but when I use arr[i] != elem, it prints out the entire array. On the other hand, if I use arr[i] == elem, it gives me the array that I don&apo ...

Switch up the link color when it pops up

Is there a method to change the link color to gray without encountering glitches like on my site, where it mistakenly shows "Quick Nav."? Click here to view the page with the glitch I only want this particular link to be bold and not any other links. He ...

Oops! Looks like there was an issue with capturing the error stack trace in Node.js. The error [ERR_HTTP_HEADERS_SENT] occurred because headers were being set after they were already

Why am I encountering this recurring error? I am working with nodejs, and my expertise in backend programming is limited, so I am struggling to identify the root cause of this issue. If anyone is familiar with this error or knows what might be causing it, ...

set up the router by defining the behavior for each route

My goal is to redirect the user back to the homepage when they click the browser's back arrow to return to the previous page. However, I'm facing an issue where I cannot go back to the previous page when I'm on the login page using the brow ...

The attempt to compare two undisclosed inputs using basic javascript was unsuccessful

In my current project, I am facing an issue with comparing two hidden input HTML elements using JavaScript onclick submit button. Despite the seeming simplicity of the task, it is not working as expected. The function that I have implemented for this purp ...

Scan through each paragraph to identify specific keywords and append them to a running list

I need to search through paragraphs for a specific word (Apple) and then add it to a list. <p>Orange</p> <p>Grape</p> <p>Apple</p> <ul id=ulist> </ul> <script> var i; var x = document.getElem ...

What is the best way to filter embedded documents based on a linked document?

I'm currently facing an issue with querying embedded documents by a referenced document in Doctrine ODM. Let's take a look at the following document structure: <?php /** @Document */ class TopCategory { /** EmbedMany(targetDocument="S ...

Ways to ensure the title changer works seamlessly for everyone

Having a title changer for elements visible in the viewport is crucial. However, the current setup only works for a single division and fails to function with multiple divisions. Click Here for Live Testing and Viewing Check out the jsFiddle for Code V ...

Typeahead limit is five suggestions at a time

Here is my code using Typeahead.js for suggestions. Everything seems to be working fine with no major issues. However, the problem I am facing is that even though there are more than 5 suggestions from the remote URL, only 5 suggestions are displayed at a ...

How can I duplicate a specific row within DataTables?

I have successfully implemented a feature that allows me to delete a selected row in my application. Now, I am looking to add functionality to duplicate or clone the selected row. The process of adding rows to DataTables can sometimes be challenging becaus ...

Can you explain the variances between creating a new date object with input as "2017-01-01" and "2017-1-1" in JavaScript?

When I use new Date("2017-01-01") in the Chrome console, the output displays its hour as 8. However, when using new Date("2017-01-1") and new Date("2017-1-01"), the hour is shown as 0. This brings up the question of how new Date(dateString) actually pars ...

Reorganizing JSON arrays with JavaScript

Exploring the realm of JSON notation as a newcomer has presented me with an intriguing challenge. I find myself in a situation where I need to reformat the current database format to align with a new structure suitable for importing into a project timeline ...

Attempting to establish a connection with the mongodb service using the Consul Connect Sidecar Proxy

Currently, I have Minikube setup with a running Mongo instance inside it, utilizing Consul + Consul Connect to mesh my services. However, I am facing issues connecting to Mongo from another service using sidecar upstreams and encountering some unusual beha ...

What steps can be taken to convert this function into a more concise, dry function?

I'm attempting to customize a typewriter effect on my webpage, and while it successfully displays predefined data, I am struggling with converting it into a function that can receive values and then display those values. I have made attempts to modif ...

Tips for incorporating MUI into your Redwood JS project

Trying to integrate MUI into Redwood JS has been a challenge for me. I attempted to run the following command in the project directory: yarn add @mui/material Unfortunately, an error message appeared in the console stating: An error Running this command w ...

What is the method for retrieving the non-strike price amount in selenium via xpath?

This is the link to the webpage I am attempting to automate: My goal is to extract the value of the non-strikethrough price (currently $ 20.00) using Selenium and an XPath locator. The following HTML snippet contains the element I am targeting: <div ...

Utilizing a form on numerous occasions prior to its submission

As a newcomer to JavaScript, I am exploring the best approach for a specific task. The task involves a form with checkboxes representing different music styles and a selector for names of people. The goal is to allow users to select music styles for mult ...