Sending a batch of data in a single POST request to MongoDB

Currently, I am developing a module that involves creating a post form to collect expense data such as name, date, amount, an image, and description. While I have succeeded in storing the post data into MongoDB for a single row of data, my goal is to allow users to submit multiple rows (i.e., multiple expenses). However, every time I attempt to submit the form with multiple instances of this data, an error occurs!

ERROR: Expense validation failed: date: Cast to Date failed for value "[ '2018-07-01', '2018-07-09' ]" at path "date"

Do you have any suggestions on how to correctly submit multiple rows of the aforementioned data?

INFO:

  1. I'm utilizing express for the server
  2. MongoDB for database

ExpenseForm.js --> (using pug template engine)

button#submitExpense(type='submit' form='addExpenseForm').btn Submit 
        // ADD EXPENSE FORM
        form#addExpenseForm(method='POST' action='/expenses').row
          div.col-md-12.add-expense-row-wrapper
            div#expenseRow.row.form-group
              input.form-control.col-md-2(type='text' name='name' placeholder='Enter Name*')
              input.form-control.col-md-2(type='date' name='date')
              input.form-control.col-md-2(type='number' name='amount' placeholder='Enter Amount*')
              input.form-control.col-md-2(type='text' name='description' placeholder='Description*')
              input.col-md-3(type='file' name='file' id='files' placeholder='Upload receipt' multiple)
              button#deleteExpenseRow.col-md-1.btn.delete-expense-row(type='button' )
                i.fas.fa-trash-alt
        div.row.add-expense-button-wrapper 
          button#addExpenseRow.btn(type='button')
            i.far.fa-plus-square

In addition, here is the Schema information:

expense.js -->

const ExpenseSchema = new mongoose.Schema({
  employee: {
    type: String,
    required: true,
    trim: true
  },
  date: {
    type: Date,
    required: true,
    default: Date.now
  },
  amount: {
    type: Number,
    required: true,
    validate: {
      validator: Number.isInteger,
      message: '{VALUE} is not an integer value'
    }
  },
  description: {
    type: String,
    required: true
  },
  file: {
    type: Buffer,
    required: true
  }
});

var Expense = mongoose.model('Expense', ExpenseSchema);
module.exports = Expense;

And here is the POST route:

index.js -->

// POST /expenses
router.post('/expenses', function(req, res, next) {

  var expenseData = { // create object with form input
    employee: req.body.name,
    date: req.body.date,
    amount: req.body.amount,
    description: req.body.description,
    file: req.body.file
  };

  Expense.create(expenseData, function(error) { // store data from form into MongoDB
    if (error) {
      return next(error);
    } else {
      console.log(expenseData);
      return res.redirect('/dashboard');
    }
  });

});

Answer №1

When the data is received, it will be in the form of an array. The name field will contain an array of all names and so on. You can loop through each item, save it to the database, and then return after saving the last item.

var employee = req.body.name;
var date = req.body.date;
var amount = req.body.amount;
var description = req.body.description;
var file = req.body.file;

var expenseData = {};

employee.forEach(function(element, index, array) {
    expenseData = {
        employee: employee[index],
        date: date[index],
        amount: amount[index],
        description: description[index],
        file: file[index]
    };
    Expense.create(expenseData, function(error) {
        if (error) {
            return next(error);
        } else {
            if (index === employee.length - 1) {
                return res.redirect('/dashboard');
            }
        }
    });
});

Answer №2

Here is a breakdown of the process:

  1. To start, gather all your data in an array format like this: expensesArray = [{data1}, {data2}, ...].
  2. Next, in your post route, include your expenses model by importing it with something similar to this: const expenses = require('thePathAndNameOfYourSchemaExportFile')
  3. Then, within your post route, call expenses.insertMany(expensesArray) method and let mongoose handle the rest. Remember to ensure you wait for the insertMany function to finish (it's advisable to have a callback in case of errors).

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

Rotating an object around another object in a 3D matrix axis using Three.js

I currently have the ability to rotate one axis. Here is the code that's working now: https://codepen.io/itzkinnu/full/erwKzY Is there a way to rotate an object on a random axis instead of just one fixed axis? Maybe something similar to this exam ...

I'm having trouble with the onImageUpload and sendFile functions in the summernote image upload feature

I have recently implemented summernote version 0.8.12 into my project. Below is a snippet of my page containing summernote: <!DOCTYPE html> <html lang="en"><head> <meta charset="UTF-8> <title>bootstrap4</title> ...

Unable to access a hyperlink, the URL simply disregards any parameters

When I click an a tag in React, it doesn't take me to the specified href. Instead, it removes all parameters in the URL after the "?". For example, if I'm on http://localhost:6006/iframe.html?selectedKind=Survey&selectedStory=...etc, clicking ...

Is there a disconnect between the input and upload methods?

While developing a website using PHP and Ajax, I encountered an issue where I need to use the GET method for inputting data when performing certain actions but have to utilize the POST method for uploading images due to its limitations. How can I retrieve ...

How to Exclude Box Geometry from Merged Geometry in THREE JS

I have over 100,000 boxes that I've added to a merged geometry. Occasionally, I need to remove some geometries from this merged structure. Is it possible for me to iterate through the position attributes in increments of either 108 or 72 vertices per ...

JavaScript Special Character Removal

It appears that a specific character is causing an issue for the library I am utilizing called xlsx-writestream when attempting to write an Excel file. Upon my investigation, I discovered that the problematic string is "pawe2". It seems fine at first glanc ...

What is the best way to ensure that messages stay saved in my app for an extended

I am looking for a way to store messages sent through my small messaging app in a persistent manner. Currently, the messages are transferred from the front-end to a Node, Socket.io, and Express back-end. A friend recommended using Enmaps (), but unfortuna ...

Guide to Triggering a Page View Event in Google Tag Manager with Angular

Previously, I manually fired the Page View Event using JavaScript from app.component.ts while directly accessing Google Analytics: declare var gtag: Function; ... constructor(private router: Router) { const navEndEvents = this.router.events.pipe( fil ...

Adding a plethora of HTML using jQuery

Struggling to create a single-page website, I've found myself relying heavily on jQuery's .append function. But surely, there has to be a more efficient method for appending large chunks of code (like tables, graphs, etc.) onto a page. Take this ...

What is the best way to trigger a function in my JavaScript code when the console log is opened on my webpage?

I have a requirement to hide the username and password fields in a form from being viewed in the console log. My plan is to listen for the console log event and then remove the values from these fields using jQuery. Any tips on how to achieve this? Thank ...

Is there a different alternative to @JavascriptInterface in Android WebView?

I understand how to invoke a Java method within JavaScript code using the @JavascriptInterface annotation. However, I am facing an issue when trying to determine which JS method should be called from Android. Currently, I am triggering an Android Dialog ...

Despite providing the correct token with Bearer, Vue 3 is still experiencing authorization issues

I am working on a project that involves Vue 3 with a Node Express back-end server and Firebase integration. On the backend server, I have implemented the following middleware: const getAuthToken = (req, _, next) => { if ( req.headers.authori ...

Loading and unloading in JavaScript to access PHP $_SESSION data

Looking to implement a javascript function on page load and unload to manage session variables. The current javascript code below (utilizing jQuery) is not functioning consistently: window.onbeforeunload = function() { $.post('Example.php?y=".$id. ...

Issue encountered during testing does not appear in final compilation and prevents tests from executing

Embarking on my maiden voyage with Angular 5... Currently in the process of setting up a Jasmine test tutorial found at this link: https://angular.io/guide/testing. However, upon initiation, an error throws me off course: ERROR in src/app/pizzaplace.serv ...

Looking to find the video code in the page source and figure out how to get the video to play

I have a requirement where I must embed the video code directly in a blog post. After figuring out the necessary code for the video and saving it in a html file named video.html, I encountered an issue when trying to upload the file to the blog. Only the ...

Incorrect spacing in the toLocaleTimeString method in Microsoft Edge's JavaScript implementation

I'm struggling to comprehend the behavior of a JavaScript code that appears to function differently in Edge. Here's what I've narrowed it down to: var testi = new Date().toLocaleTimeString(); var len2 = testi.length; alert(len2); In Edge, ...

Click on a specific button within a DataTable row

I am working with a dataTable that fetches data from the database using Jquery. In each row, there are two buttons for accepting or rejecting something. My goal is to make the accept button disappear when rejecting and vice versa. public function displayT ...

The process of updating a nested object property in Redux and React

Initially, the user object is established with properties such as name, color, and age using the SET_USER method. I need to modify the name property within the user object utilizing UPDATE_USER_NAME. However, despite trying a nested loop within UPDATE_USER ...

Example of fetching Pubnub history using AngularJS

I am not a paid PubNub user. I am utilizing the example code for an Angular JS basic chat application from PubNub, and I want to access the chat history. This specific example can be found on the PubNub website. git clone https://github.com/stephenlb/an ...

producing imperfections on tiny items

I am currently working on rendering a texture onto a cylinder using threeJS. While it usually works well, I have encountered some strange artifacts when the radius of the cylinder is set to very low values (such as 0.0012561892224928503 in the image attac ...