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

Exploring the Intersection of Windows 8 Store Applications and jQuery: Leveraging MSApp.execUnsafeLocalFunction

Developing a Windows 8 JavaScript Store App (using Cordova) has led to some complications when using jQuery. It seems that in order to utilize certain functions, I have had to modify the jQuery library by adding: MSApp.execUnsafeLocalFunction While this ...

Can you explain the concept of mounting as defined in the Express documentation?

Over on this page, the definition of [app.use] states that it "Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path." I'm curious about the t ...

Having trouble getting your Ajax script to function correctly when submitting a form?

I am currently facing an issue where I am loading a partial page, but I do not want the form on this page to redirect when the save button is clicked. I am unsure if I am using the script correctly. I would like to post to the controller when the submit b ...

What is the method for producing an li and anchor tag using a list object?

Here is the response I received from my web service, and now I need to transform it into a list item tag: {"d":[{"name":"ttt","url":"bbbb"},{"name":"uuu","url":"ppp"}]} How can I create li tags based on the above output? This is the desired format for t ...

NuxtJS using Babel 7: the spread operator persists in compiled files

Struggling to get my NuxtJS app functioning properly on IE11. Despite multiple attempts to configure Babel for compatibility, spread operators are still present in the built pages files, suggesting that Nuxt code is not being transformed correctly. Below ...

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

What is the sequence of the middlewares for error handling and handling of 404 errors?

The express.js website has confused me with contradictory statements regarding error-handling middleware. According to one page, you should define error-handling middleware last, after other app.use() and routes calls. However, another page states that you ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...

Mastering the art of building a datepicker: A comprehensive guide

Looking for advice on how to create a datepicker in HTML without relying on bootstrap or pre-built JavaScript and CSS. I am interested in learning the process from the ground up and understanding how developers have designed these tools. I am specifically ...

Preserve the ajax controls while uploading files

I encountered a minor issue with file uploading. When I click the upload button, a window (ajax powered) pops up for selecting a file. However, as soon as the file is uploaded to the browser, the page reloads and the window closes, leaving me without the ...

NodeJs: The local server seems to be stuck on loading and is not displaying any information

I am currently working on a new project that involves using JS, NodeJS, and SQL. While this is not my first time working with these technologies, I am facing an issue where the backend endpoint keeps loading when I try to test it. The only difference this ...

Entering a new row and sending information through ajax

I'm looking for some help with a web page I have that includes a particular table structure: **Check out my Table*:* <table id="staff" class="table"> <thead> <tr> <th>First Name</th> <th>Last Nam ...

After making 5 Ajax get requests, there is no response being received

Currently, I'm facing an issue when trying to retrieve information from the MongoDB server to the frontend using an AJAX GET request. Everything works smoothly until I attempt to call the JavaScript function multiple times. Strangely, if I call the fu ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Error message received from GitHub when attempting to create a repository through the REST API states that JSON cannot

I am currently in the process of learning how to use REST APIs for GitHub, and my current project involves creating a new repository using JavaScript. Below is the function I have written for this purpose, which includes generating a token and granting all ...

The Aggregation Projection Query encountered an error due to an unrecognized expression

Error in $project :: caused by :: Unrecognized expression '$$varientPricePoint.ppId' { "pricepoint": { "$filter": { "input": "$OriginalPricePoints", "as": "varien ...

What is the best way to invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

Guide for implementing onclick event for info boxes in push pins on Bing Maps using ReactJS

I have successfully placed all the coordinates on the map using pushpins, but now I want to create an event that shows an infobox when a pushpin is clicked. Could someone provide an example of how to hide infoboxes and only show them when a pushpin is cli ...

Experiencing trouble with the integration of react native Vector icons in a current project

I'm encountering an issue with React Native Vector Icons. The error message I'm receiving says: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You l ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...