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:
- I'm utilizing express for the server
- 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');
}
});
});