我已经设置了一个上传 .csv 文件的路径,验证接收到的数据,检查数据库中是否存在任何行,并在执行所有验证检查后最后上传数据。
以下是有问题的路线:
...
const Customer = require('../models/Customer');
const fs = require('fs');
const multer = require('multer');
const csv = require('fast-csv');
router.post('/customers/csv', upload.single('file'), async (req, res) => {
const errors = [];
const fileRows = [];
const existRows = [];
const count = 1;
fs.createReadStream(req.file.path)
.pipe(csv.parse({ headers: true }))
.validate(data =>
// Data validation for each field...
)
.on('error', error => console.error(error))
.on('data-invalid', (row, rowNumber) =>
{
errors.push(`Invalid [rowNumber=${rowNumber}] [row=${JSON.stringify(row)}]`)
console.log(`Invalid [rowNumber=${rowNumber}] [row=${JSON.stringify(row)}]`)
}
)
.on('data', async function (row) {
if(await Customer.exists({$or: [
{srn: row.srn},
{telephone: row.telephone},
{claim_id: row.claim_id},
{receiver_id: row.receiver_id}
]})) {
// This doesn't store data so long as I'm using async/await
// but I need the await for the mongoose query
existRows.push(row)
} else {
fileRows.push(row) // This doesnt work so long as I'm using async
}
count++;
})
.on('end', (rowCount) => {
fs.unlinkSync(req.file.path);
if(errors.length !== 0) {
req.flash(
'error_msg',
`Upload failed! Parsed ${rowCount} rows with ${errors.length} bad rows at rows:`
)
return res.redirect('/admin/customers/csv')
}
if(existRows.length !== 0) {
req.flash(
'error_msg',
`Error: ${existRows.length} rows already exist. Kindly edit and try again.`
)
return res.redirect('/admin/customers/csv')
}
fileRows.forEach(async customer => {
//Execute an insertion or save
})
})
})
不幸的是,我似乎无法访问我存储在 on.('data'...) 部分之外的existsRows或fileRows数据,并在 on.('end'...) 部分中使用它们。
我认为这一定是我如何在那里设置异步/等待的问题?