Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assistance to do it as a single data dump so I can upload ALL my casinos at once.

Below is the functioning route for posting a single object:

router.post('/post', async (req, res) => {
console.log(req.body);
const casinoData = new Casino({
    casino: req.body.casino,
    table_and_other: req.body.table_and_other,
    poker: req.body.poker,
    slot_machines: req.body.slot_machines,
    total_gaming_win: req.body.total_gaming_win,
    year: req.body.year,
    month: req.body.month,
    combined_date: req.body.combined_date
})

try {
    const newCasino = await casinoData.save()
    res.status(201).json(newCasino)
} catch (err) {
    res.status(400).json({ message: err.message})
}
})

I am aware that using mongoimport could be a more efficient way to handle this, but it also comes with its own set of challenges.

Thank you

Answer №1

In agreement with @JDunken's suggestion, one can traverse through the POST body as an array and perform bulk insertion. For efficient processing, utilizing insertMany is recommended. When dealing with a large volume of data, it is advisable to establish a reasonable limit for the number of records per request and execute API calls in batches. Validation can be included, but Mongoose will handle validation based on the defined schema. The approach to handling validation errors is subjective. It is essential to familiarize yourself with the options such as ordered and rawResult.

router.post('/post', async (req, res) => {
  // Precautionary check to ensure req.body is an array, depending on error handling requirements
  const casinos = req.body.filter(input => isValid(input));

  try {
      const insertedCasinos = await CasinoModel.insertMany(casinos, { ordered: false });
      res.status(201).json(insertedCasinos)
  } catch (err) {
      res.status(400).json({ message: err.message})
  }
})

const isValid(input) {
    let valid = true;
    // Implement input validation logic here
    return valid;
}

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

Using Angularjs to dynamically generate and submit tables

I can't seem to figure out this specific situation Data: $scope.MyItem = [ { "__v": 0, "myItemId": "55ed819caefe18e81ffbd2d2", "itemId": "56fec8abb192c870117ed393", "january": 1, "february": 1, ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Showing content based on the route - Angular

I'm struggling to hide the navbar based on a specific route in my application. I have managed to subscribe to the route changes, but I am having difficulty changing the display property accordingly. Here is what I have so far: export class AppCompo ...

Creating a TypeScript generic type for the "pick" function to define the types of values in the resulting object

I am facing an issue while writing the type for the pick function. Everything works smoothly when picking only one key or multiple keys with values of the same type. However, if I attempt to pick a few keys and their values are of different types, I encoun ...

Unearthing the worth of the closest button that was clicked

I am currently working on a profile management feature where I need to add students to the teacher's database. To achieve this, I am using jQuery and AJAX. However, I am encountering an issue where clicking the "add" button for each student listed on ...

What could be causing the Logical Or to fail in my function?

How can I adjust the following sample code to check for not only empty keys but also null and undefined? I attempted: (obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined) However, that approach caused issues and did not function c ...

Access a file from a specified route within Express

Recently, I created a custom Node module that requires a configuration file in CSV format. My goal is to implement this module within an Express Route module; however, I am encountering difficulties related to the loading of the configuration file. Should ...

Setting the default selection in AngularJS based on the URL entered

I've encountered an issue with a dropdown menu in my AngularJS version 1.4 application. The dropdown menu contains links to different sections of the page. The problem arises when I directly enter the page URL - instead of selecting the correct link f ...

I managed to pass an array of data to the client using EJS, but I encountered an issue trying to access the array on the client side after adding an index value

When I pass data received from an API to the client using EJS, I am struggling to access the JSON array on the client side. On the server side, I successfully send the returned data to the client like this: fetch(url) .then(res => res.json()) .the ...

Is there a way to verify the presence of a selector in Puppeteer?

How can I use Puppeteer to check if #idProductType exists and if not, assign producttype to ""? I have tried multiple solutions but none seem to work. const urls = [myurls, ...] const productsList = []; for (let i = 0; i < urls.length; i++) ...

``Is there a way to effectively assess the Angular UI-Grid cellTemplate function in the attribute value only when it is displayed

Utilizing angularjs and ui-grid with a custom cellTemplate, each cell contains an object referred to as COL_FIELD. This object is passed to a function that generates an image data URI used in the src attribute of the cellTemplate to display images within e ...

Combining all elements of my application into a single HTML, JS, and CSS file

My AngularJS app has a specific structure that includes different directories for each component: theprojectroot |- src | |- app | | |- index.html | | |- index.js | | |- userhome | | | |- userhome.html | | | ...

What are the steps to turn off response data compression in an Express server?

How can I receive the 'Content-Length' response from the server without gzip compression enabled? I am using a compression middleware for this purpose: const shouldCompress = (req, res) => { if(req.headers['x-no-comprassion']) { ...

The Interactive Menu Toggler: A jQuery Solution

$(window).on('resize', function() { if ( $( window ).width() > 768 ) { $('#menu-main-navigation').show(); } }); $('#nav-toggle').on('click', function() { // start of the nav toggle $('#m ...

Utilizing react js computed property to retrieve a state value: A guide

I recently developed a fading text component where the header fades in and out using transition opacity CSS and a visibility state. To simplify my code, I decided to create a fading text group component that can handle multiple fading texts at once. My goa ...

deleting an object from an array in JavaScript

I have a collection of objects that looks like this: [{ "id": 2, "price": 2000, "name": "Mr Robot T1", "image": "http://placehold.it/270x335" }, { "id": 1, "price": 1000, "name": "Mr Robot T2", "image": "http://placehold.it ...

The clearfix feature is ineffective when using AngularJS

<ul class="dropdown-menu wm_search_div" ng-show="searchDivShow"> <li ng-repeat="user in searchUserList"> <a href="javascript:void(0);" class="wm_clearfix3"> <img ng-src="{{user.faceIcon}}" class="pull-left wm_se ...

I have to convert a JSON string that I received from a server into a particular JavaScript object

Hey everyone! I wanted to share some code I've been working on: $.ajax({ url: '@Url.Action("GetMerchantUsers", "Merchant")', dataType: 'json', success: function (json) { var mappedTasks = $.map(JSON.parse(json ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...

Pinchin opts for alternative methods over utilizing the Hammer library for calls

After downloading Hammers.js version-1.0.10, I have been trying to call the 'pinch in' function from the JavaScript file but it is not executing. I suspect there may be a problem with the library as I have tried downloading another one, but the s ...