Updating and adding fields within a nested object in mongoDB

In my mongoDB document, I am looking to insert additional data:

{
    "_id" : "7KufvMQFyyeuKFP68",
    "target" : {
        "10" : "true",
        "id" : "ePce6fBAHx9KeKjuM"
    }
}

I want to update the existing fields in target or add new ones if needed. Here is the code I attempted:

var result = { "30": "true", "id" : "ePce6fBAHx9KeKjuM" };

Collection.upsert(
    { _id: id }, 
    { $set: { target: result } }
);

However, when I ran this code, the value of 10 was replaced by 30, while what I actually wanted was:

{
    "_id" : "7KufvMQFyyeuKFP68",
    "target" : [{
        "10" : "true",
        "30" : "true",
        "id" : "ePce6fBAHx9KeKjuM"
    }]
}

Answer №1

If you're looking to update an array of objects, ensure that the type is set to an array in your schema with the target field as the array. To update the array, simply select it by the ID or field of your choice.

The following code snippet locates the specified field and inserts "30" : "true", while preserving the rest of the object within the array. Hopefully, this solution proves helpful:

const userSchema = new mongoose.Schema({
    name: String,
    target: Array
});

const User = mongoose.model("User", userSchema);

const user1 = new User({
    name: "jack",
    target: [{
        "10": "true",
        "id": "ePce6fBAHx9KeKjuM"
    }]
});

user1.save(user1, (err, user) => {
    console.log(user);
});

User.findOneAndUpdate(
    {"name": "jack"},
    {safe: true, upsert: true, new: true},
    (err, model) => {
        model.target[0]["30"] = "true";
        console.log(model.target);
    }
);

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

Updating data using @Query with Spring Data MongoDB

I am looking to update a specific flag in MongoDB efficiently without having to query all the documents and then updating them back into the database. I want to perform a direct update, similar to how it's done in the MongoDB terminal, for my use case ...

Include new options to the select box only if they are not already listed

I'm currently working on a situation where I need to transfer items from one select element to another, but only if they are not already in the second select: $('#srcSelect option:selected').appendTo('#dstSelect') My challenge is ...

Using Node Express to pass the results of a function outside of a forEach loop

Looking for assistance with passing results from an async forEach function to ejs. Any help would be greatly appreciated! router.get('/', (req, res) => { Block.find({}).populate('servers').exec((err, foundBlocks) => { if(err){ ...

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

Display choices for selection from database depending on parent selection

I am currently working on a form that includes two selection boxes. Both of these boxes are populated with options from my database using PHP. The first selection box displays a list of books ordered by their ISBN in the following format: <ISBN> - ...

Best method to determine if three points in time are less than thirty minutes apart

In the form, there are 3 date/time input boxes with a requirement that the user cannot select times within half an hour of each other. I successfully converted all values to epoch format using a Javascript version of strtotime. However, I am unsure how to ...

Is the toString() method explicitly invoked by Number() if the value is not of type number or string? (such as a function)

Looking for clarification on the behavior of parseInt() compared to the Number() constructor called as a function. I want to confirm if this is reliable and if there's an official reference to support it. Below is sample code: let adder = (function ...

How can I create a top-notch chrome extension to enhance shopping deals?

I am in need of creating a Chrome extension that will showcase the latest offers and coupons whenever I visit any affiliate store like Amazon, AliExpress, Flipkart, Myntra, etc. Upon visiting their website with my extension installed, a popup with offers ...

Utilizing Flask for analyzing characteristics of text presented in JavaScript

My current variables consist of: myfruits = ['Apple', 'Banana', 'Lemon'] havefruit = [True, True, False] If the user input changes the values in havefruit, I need to implement JavaScript in my HTML file to display the entrie ...

The issue with Google Maps API not loading is being caused by a problem with the function window.handleApiReady not being

Having trouble with the Google Maps API, specifically encountering an error during page load that says window.handleApiReady is not a function, even though it definitely exists. Examining the code snippet below reveals its usage as a callback function: ...

activating javascript function in rails when the page reloads

I have a rails4 app and I'm looking to implement some specific JavaScript events when the page loads, but only if the user is coming from a certain page. On the post#index page, all comment replies are initially hidden. When a user clicks on a specif ...

Implementing dynamic checkbox values depending on a selection from a dropdown menu in Angular

In my checkbox list, I have various Samsung mobile models and two offers available. $scope.offers = [ { id: "as23456", Store: "samsung", Offer_message:"1500rs off", modalname: "Samsung Galaxy You ...

Utilizing JavaScript to create a single selection from two Listboxes

Seeking assistance with integrating ASP.NET (C#) code. In my web application, I have implemented two listboxes - one displaying a list of companies fetched from the database (lstCompanies), and the other allows users to filter these companies (lstFilter). ...

Differences between count() and length() methods in Protractor

When it comes to determining the number of elements inside the ElementArrayFinder (which is the result of calling element.all()), you have two options according to the documentation: $$(".myclass").length, detailed here: This approach involves using ...

What is the best way to create a function that automatically resumes audio playback 3 seconds after the pause button is clicked?

I am looking to develop a basic webpage with an autoplay audio feature. The page would include a "pause" and "play" button. I aim to implement a function where clicking the "pause" button would stop the audio, but after 3 seconds, it would automatically re ...

Accessing the value of a hidden field within an ng-repeat loop when binding to an HTML table

I am working on a project where I have an HTML table with data being bound from AngularJS. The structure looks something like this: <tr ng-repeat="item in List| filter: { MachineType: 'Physical' }"> <td>{{item.MachineType}}< ...

identifying unused class names within an HTML codebase

Is there a way or tool available for detecting unused class names in HTML code? I have some HTML code with old Bootstrap, jQuery, and personalized CSS styles like below: <div class="clear fot-her likes tab-sub">content</div> But I n ...

What is the best way to display an object in ReactJS?

My Object is: https://i.sstatic.net/QsQ1X.png I need to extract data from the recette-... endpoint in base64 format const articleList = Object.keys(this.state.users).map(key => { Object( this.state.users[key].recettes).map(data => { / ...

Access information through token-based verification

Just starting out in this area of development, a colleague shared some information with me on how to retrieve the database. I'm feeling a bit lost as to what to do next. curl -X GET -H "Authorization: Token token=xxxxxxxxxxxxxxxxxxxxxxxxx" "https://w ...

My JavaScript functions are not compliant with the HTML5 required tag

I am currently developing input fields using javascript/jQuery, but I am facing an issue with the required attribute not functioning as expected. The form keeps submitting without displaying any message about the unfilled input field. I also use Bootstrap ...