Updating MongoDB in Mongoose by utilizing two arrays

I've recently started using mongodb and have been having trouble finding the information I need in the documentation (Maybe I just didn't look in the right places).

Let's say I have two arrays:

ids = [1, 2, 3, 4]

values = [12, 33, 44, 11]

Right now, I'm going through each id in the list and updating the database for every entry, which feels very inefficient:

For this, I'm using an object for each iteration (Here's a simplified example):

update['values']['duration'] = values[i];

This is how I insert into the DB

await CollectionName.updateOne({ids: ids[i]}, {$set: update});

Any suggestions? Thanks! :)

Edit: Example 2:

ids = [4, 7, 9]

values = [
{"array":
    "preference" : "test",
    "1Duration" : 55,
    "2Duration" : 66
},
{"array":
    "preference" : "test",
    "1Duration" : 22,
    "2Duration" : 33
},
{"array":
    "preference" : "test",
    "1Duration" : 78,
    "2Duration" : 11
}
]

Answer №1

Sample structure for your code:

User.findOneAndUpdate(
                    { },      //Here you can specify the record to insert into                    
                    { $push: { ids , values  },
                    (err) => {
                         if (err) throw console.log('errors encountered');
                            console.log('record created')

                });

Answer №2

In this scenario, the $in operator can be utilized.

await CollectionName.updateMany({ids: {$in: ids}}, {$set: update});

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 method for executing raw mongoDB commands with mongoose library?

Is there a way to adjust the mongodb's-sort-buffer-size through the following command? db.adminCommand({setParameter: 1, internalQueryExecMaxBlockingSortBytes: <limit in bytes>}) If so, how can this command be executed using the mongoose libra ...

Updating state using the react `setState()` function will automatically trigger a re-render

I am currently working on a large form using React and material-ui. The form implements two-way binding to update the state when input changes occur. Interestingly, changing any input field triggers updates in all components (as observed through TraceRea ...

Comparing ASP.NET Core and Node.js: A Closer Look at Their Similar

After working with Node.js for some time, I have gained a deep understanding of how it operates internally, including the event loop and other aspects. However, I can't help but notice that ASP.NET Core bears a striking resemblance to Node.js. ASP.NE ...

What causes a small variation in the image composition when displaying a PNG file with drawImage?

In the code provided, the image file named "img" was created using Gimp. This image contains a color pixel : rgba=176 99 234 167. However, when displayed in a particular context and then its composition retrieved using getImageData, there is a sligh ...

Working with JavaScript to extract data from a JSON array

I am currently working with a MySQL database that contains a table of latitudes and longitudes along with associated data. My goal is to create a Google Map and utilize JavaScript to parse the JSON string. Despite searching on various platforms, including ...

Having issues installing Parcel through npm - Encountered an error while parsing package.json information

After creating a package.json file using the command npm init in my project folder, I proceeded to run npm i parcel --save-dev which resulted in an error message: C:\Users\XPRESS\Desktop\starter>npm i parcel --save-dev npm ERR! code ...

Tips for updating one-time binding data in AngularJS

I am currently facing an issue with a div that displays details such as mobile number, name etc. in the format: {{::mobilenumber}}, {{::name}} Within this div, there is a button that when clicked should populate the same values in a new form However, des ...

The overflow:scroll property fails to function properly after I insert additional content into the div

My webpage includes a div element with initial styles and no content: #chatwindow { width: 500px; height: 50px; overflow-y: scroll; ...

Activate the click action within the option directive

I'm trying to activate a click event when options are clicked instead of using the change event for specific reasons. Below is my code snippet: .directive('itemOptions', [ function() { return { ...

Execute the script when the document is fully loaded

Is there a way to show a dialog in jQuery when the document loads without using <body onload="showdialog();">? Can the javascript code be placed in the main div or footer div to work like the onload event? <body onload="$('#dialog').sli ...

Refresh the page using a promise in Angular after a delay of 3 seconds

Currently, I am working on enhancing the functionality of the login page. In case a user enters an incorrect login and password combination, my goal is to have the page automatically reload after 3 seconds. Despite my best efforts, I have encountered chall ...

How is it possible to encounter a Javascript unexpected token ] error within an HTML code?

While working on my project, I encountered a JavaScript error in the console of Chrome. The error message stated "Unexpected token ]" and it was pointing to a specific line of raw HTML code. I am puzzled about what could be causing this issue. Unfortunatel ...

Sort through a collection based on its individual components

Displayed is an array within a loop: I am looking to filter this array based on the [date-begin] and [date-end] values For example, if I specify start date = 2015-06-29 and end date = 2015-08-29 then only array data falling within this range should be sho ...

Utilize Pascal to add user input into an array

Hello, I am currently working on improving my skills in functional programming. I have decided to start by experimenting with different languages like Pascal, Scheme, and ML. I began my journey with Pascal, attempting to insert user input into an integer a ...

Experiencing the error message "Uncaught TypeError: Cannot read property 'push' of undefined" unexpectedly popping up at random intervals

Hey there, I've encountered an issue while trying to fetch data from a URL and populate it into an array. The process involves pushing the fetched data into the "data" property of each element in the array, and then repeating this process recursively. ...

Is there a way to merge all this data into a single Object?

This particular situation is quite complex. Let's consider the following scenario: I have two JavaScript objects that are fetched via REST calls, using two different callbacks. So, we have: call1() - POST method - parsed JSON to JavaScript object, ...

Give a CSS Element a specific class

Can all h3 elements be styled with the class responsive-heading using only CSS? Take a look at the CSS snippet provided for more clarity: h3 { .responsive-heading } /* The responsive-heading class is defined in another CSS file and includes: .respons ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

Troubleshooting: Inability of Angular2 Component to access class property within template

Here is the code snippet that I am currently working with: post.component.ts: import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { JobsService } from '../jobs.service'; @Component({ ...

At what point is it appropriate to terminate this database connection?

Currently, I am in the process of creating a script to update all entries within a database. To start off, I have implemented a logging feature to keep track of all modifications. const MongoClient = require('mongodb').MongoClient.connect("mong ...