我正在处理此模块,它是一种邮政表格,用于收取费用(姓名,日期,金额,图像和说明)。我已经弄清楚了如何将发布数据放入一行数据的mongo中,但是我希望用户能够提交多行(即多次支出)。不幸的是,当我尝试使用该数据的多个实例提交表单时,出现错误!
错误:费用验证失败:日期:路径“日期”的值“ ['2018-07-01','2018-07-09']”的强制转换为日期
是否有关于如何正确提交上述数据的多行的想法?
INFO:
ExpenseForm.js->(使用哈巴狗模板引擎)
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
也忘记了我的架构
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;
和后路线 index.js->
// POST /expenses
router.post('/expenses', function(req, res, next) {
// Expense.getExpenses({
// name: req.body.name,
// date: req.body.date,
// amount: req.body.amount,
// description: req.body.description,
// file: req.body.file
// }, 10, function(err, post) {
// if (err) {
// return next(err);
// }
// console.log(req.body);
// res.json(post);
// });
// create object with form input
var expenseData = {
employee: req.body.name,
date: req.body.date,
amount: req.body.amount,
description: req.body.description,
file: req.body.file
};
// store data from from into mongo
Expense.create(expenseData, function(error) {
if (error) {
return next (error);
} else {
console.log(expenseData);
return res.redirect('/dashboard');
}
});
});
答案 0 :(得分:0)
因此,数据将以数组形式出现。 name
将包含所有名称的数组,依此类推。您可以遍历所有对象并保存在数据库中,然后在保存完最后一项后返回。
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');
}
}
});
});
答案 1 :(得分:0)
步骤如下: