Import mongoose object list

0

I'm trying to save data from a csv file in mongoDB, using mongoose.

I need to read row by line, generate an object from that row and supplement it with other data, which comes from the user login session.

To work with the csv file, I'm using fast-csv. As can be seen in the code below:

router.post('/importar', async function (req, res) {
    let arquivo = req.files.csv;
    let newAluno = new Aluno()
    let iesUser = req.user.ies
    let iesSiglaUser = req.user.iesSigla

    csv.fromString(arquivo.data, { headers: true, ignoreEmpty: true })
        .on("data", function (data) {
            newAluno.nome = data.nome
            newAluno.codigo = data.codigo + '@' + iesSiglaUser
            newAluno.email = data.email
            newAluno.curso = data.curso
            newAluno.iesSigla = iesSiglaUser
            newAluno.ies = iesUser
            newAluno.senha = data.codigo + '@' + data.codigo
        })
        .on("end", function () {
            Aluno.createAluno(newAluno, function (err, aluno) {
                if (err) {
                    req.flash('error_msg', 'Erro ao cadastrar os alunos');
                    res.redirect('/aluno/importar')
                }
                console.log(aluno);
                req.flash('success_msg', 'Alunos cadastrados com sucesso');
                res.redirect('/aluno/importar')
            })
        })
})
When I use the ".on ()" function it saves only the data of the last line, when I use the ".once ()" function it saves the data of the first line.

In order to solve this, I tried to create a list with these objects and to save within a for, each object of this list, but mongoose accuses the following error:

parallelSaveError: Can't save() the same doc multiple times in parallel. Document: null

Does mongoose not allow saving lists of objects? How can I solve this problem? I'm already packing for 2 days.

    
asked by anonymous 26.07.2018 / 16:19

0 answers