Updating arrays with empty fields in mongodb

I need help updating an array in my database which currently doesn't have any fields. Can anyone suggest a way to add fields to the existing empty array?

Schema

      const UserSchema = new Schema({
        User: [{

         Name:{
           type: String,
        },

        Email:{
           type: String,
        },

       }]
    })
      

The array is currently saved in the database but it's empty like this

saved database

      "id": 101,
      "User":[], 

Below is the code I've used to update the array

           User.update({id: 101,},
             {
             $push:{
                 user:{
                      Name: "Kevin",
                      Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="266d43504f4866414b474f4a0845494b">[email protected]</a>",
                     },
                   }
             },(err, data)=>{
                console.log(data)
             })

However, upon running this code, the array doesn't seem to update. Can anyone provide guidance on how to resolve this issue?

Answer №1

db.getCollection('test2').update({
  "id": 101
},
{
  $push: {
    User: {
      $each: [
        {
          "name": "gibbs"
        }
      ]
    }
  }
})

Adding new data to an array using the $each operator. It is important to note that field names are case sensitive in MongoDB, so User should be capitalized.

Click here for more information

Result:

/* 1 */
{
    "_id" : ObjectId("5f08753ce96d8884b6bcc92e"),
    "id" : 101,
    "User" : [ 
        {
            "name" : "gibbs"
        }
    ]
}

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 send props and trigger a function with a single onclick event?

Is there a way to receive a prop and activate a function using the same onclick event? In the navbar.js file, the props are passed like this: <Hamburger menuOpen={this.ToggleMenu} /> In the Hamburger.js file, the props are received. Currently, the ...

What is the process for obtaining documents that contain arrays with duplicate elements in them?

Looking at my MongoDB documents below, I have identified a pattern: { _id: ObjectId('09de14821345dda65c471c99'), items: [ _id: ObjectId('34de64871345dfa655471c99'), _id: ObjectId('34de64871345dfa655471c91&apo ...

Tips for transferring state value from a form to a child modal

As a newcomer to React, I am uncertain about the best approach to take in my project. Specifically, I have a modal component that should appear once the user fills out a form and clicks on the Preview Voucher button to display the entered values. Below, yo ...

Angular: Handling window resizing events in your application

To handle window resize events in a non-angular application, we typically use the following code: window.onresize = function(event) { console.log('changed'); }; However, in angular applications, it's not recommended to directly acc ...

disable the button border on native-base

I'm attempting to enclose an icon within a button, like so: <Button style={styles.radioButton} onPress={() => { console.log('hdjwk'); }}> <Icon ...

Only one of the two scripts is functioning as intended

I'm facing an issue with two different scripts - the first one doesn't seem to work while the second one does. Oddly enough, when I remove the second script, the first one starts working. Can you help me find a solution? <script> // Ta ...

Guide on how to call a function in ascx code-behind using JavaScript within the framework of DotNetN

Currently, I am facing an issue with my module that involves submitting data to a SQL table in a database using code behind. My validation is done through javascript, and when a button is clicked and the data is valid, a div is displayed. However, the pr ...

Getting the row number associated with a particular value in a MySQL fetch row, array, or assoc result using PHP

In PHP, I have retrieved a SQL result ($myresults = mysql_fetch_… either assoc/row/array) that looks like this: SELECT table1.name as name, sum(table2.numbers) as numbers FROM table2 INNER JOIN table1 ON table2.fk_id = table1.id GROUP BY name ORDER BY ...

Develop search bar button and file directory components

Within this application, there is a search engine designed to scan through the file tree for specific content. The goal is that upon entering a search query and clicking the Search button, the file tree will filter and display the relevant information. Cu ...

Get rid of the first line of PowerShell output

While attempting to retrieve the session ID, I encountered an issue where the output displayed the column name instead of the actual ID. When using a match function, the correct value is returned since the output does not include the column names. Is ther ...

Jquery selector failing to target correct <form> element within Shopify theme

I'm feeling a bit lost here! Trying to zero in on a form within my page and utilize jQuery's serializeArray() function to extract all the values from said form. <div class="page-width"> <header class="section-header ...

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

Creating interactive functionality for textareas and input fields in Vue: A beginner's guide

I need assistance with creating a function where changing the input field will also automatically update the textarea's value. I have successfully implemented Vue js for updating the input field based on the textarea, but I am struggling to reverse th ...

How can scripts communicate with one another through passing arguments?

"scripts": { "dev": "npm run development", "development": "run-something", .... When invoking my script, I use the following command: npm run dev This is a convenient shortcut that executes the standard command npm-run-development. Is there ...

What is the most effective method for storing an object in React?

I am facing an issue with storing my Object of my Checkout-Cart in a React Variable. I attempted to use the useState Component, but unfortunately, it did not work. Here is the object that I receive from my NodeJs Backend : [ { product_uuid: '3b ...

Deactivate the Submit button when the database field has been populated

My form includes a submit button. The Submit button should be disabled if the "price" for a specific product is already filled: PHP Code <?php $host="localhost"; $username="root"; $password=""; $db_name="ge"; $con=mysqli_connect("$h ...

Is it possible to set up a local version of the Firebase database for development testing?

Can the actual code on Firebase database be avoided during development by running a local instance and developing using that, similar to other MongoDB and MySQL databases? ...

Allow the array to update only once when using setState

I am encountering an issue while trying to update an array within a setState function. Initially, there is an array within the main component named "myCourses" that contains information about a student's courses. Subsequently, there is a modal compon ...

Having some trouble implementing the functionality of hiding a data series in HighCharts using `{ data: [], visible: false }` notation

I am currently working on creating a graph that displays multiple series obtained from JSON data in a MySQL database. My goal is to have the graph show only one series initially. Thankfully, HighCharts offers an option to achieve this as demonstrated below ...