简体   繁体   中英

Mongodb return populated object but save empties some fields

So I have a little problem, when I post to save data on the database, it does everything OK and returns the object as it should be, but when I get it from the database it comes with an empty array and I know that I save this array with data.

This is the code:

Controller

    router.post("/semestre", function(req, res) {
    var req = req;
    var res = res;
    console.log("hello! routed to /semestre [create]");
    //build needs
    var newSemestre = new semestreModel();
    //fecthing materias


    newSemestre.nome = req.body.nome;
    if (req.body.materias.length > 0) {
        var materias = JSON.parse(req.body.materias);
        materias.forEach(function(materia, index) {
            //building needs  
            var newMateria = new materiaModel();
            //fechting avaliacoes
            newMateria.nome = materia.nome;
            newMateria.avaliacoes = [];
            if (materia.avaliacoes.length > 0) {
                materia.avaliacoes.forEach(function(avaliacao, index) {
                    //console.log("avaliacao:" + avaliacao.nome);
                    //building nedds
                    var newAvaliacao = new avaliacaoModel();
                    newAvaliacao.nome = avaliacao.nome;
                    newAvaliacao.nota = avaliacao.nota;
                    newAvaliacao.save(function(err, availacao) {
                        if (err) {
                            console.log("@semestres [create] - saving avaliacao has error");
                            res.send({ erro: true, msg: "Oops! alguma coisa está errada!" });
                        } else {
                            newMateria.avaliacoes.push(avaliacao._id);
                        }
                    });
                });
            } else {
                console.log("avaliacoes:[]");
            }

            newMateria.save(function(err, materia) {
                if (err) {
                    //console.log(err);
                    console.log("@semestres [create] - saving materia has error");
                    res.send({ erro: true, msg: "Oops! alguma coisa está errada!" });
                } else {
                    newSemestre.materias.push(materia._id);
                }
            });
        });
    }

    newSemestre.save(function(err, semestre) {
        if (err) {
            //console.err(err);
            console.log("saving semestre has error");
            res.send({ erro: true, msg: "Oops! alguma coisa está errada!" });
        } else {
            //console.log(semestre);
            res.send(semestre);
        }
    });

});

Schemas

var materia = {
    nome: String,
    notaFinal:Number,
    semestre_id:String,
    frequencia:Number
  };
var MateriaSchema = new Schema(materia );

var model = {
    nome: String,
    materias: [String],
    completo: Boolean
};
var SemestreSchema = new Schema(model);

var model = {
    nome: String,
    materia_id: String,
    nota: Number
};
var AvaliacaoSchema = new Schema(model);

Again everything works fine, but it just saves an empty array of materias when creating a newSemestre .

Try the following way :-

var newSemestre = new semestreModel();
//fecthing materias

newSemestre.nome = req.body.nome;
if (req.body.materias.length > 0) 
{
    var materias = JSON.parse(req.body.materias);
    materias.forEach(function(materia, parentIndex) 
   {
        //building needs  
        var newMateria = new materiaModel();
        //fechting avaliacoes
        newMateria.nome = materia.nome;
        newMateria.avaliacoes = [];
        if (materia.avaliacoes.length > 0)
        {
            materia.avaliacoes.forEach(function(avaliacao, index)
           {
                //console.log("avaliacao:" + avaliacao.nome);
                //building nedds
                var newAvaliacao = new avaliacaoModel();
                newAvaliacao.nome = avaliacao.nome;
                newAvaliacao.nota = avaliacao.nota;
                newAvaliacao.save(function(err, availacao) 
                 {
                    if (err) {
                        console.log("@semestres [create] - saving avaliacao has error");
                        res.send({ erro: true, msg: "Oops! alguma coisa está errada!" });
                    } else {
                        newMateria.avaliacoes.push(avaliacao._id);
                    }
                });
            });
        }
        else
        {
            console.log("avaliacoes:[]");
        }

        newMateria.save(function(err, materia) 
        {
            if (err) 
           {
                //console.log(err);
                console.log("@semestres [create] - saving materia has error");
                res.send({ erro: true, msg: "Oops! alguma coisa está errada!" });
            } 
            else
            {
                newSemestre.materias.push(materia._id);

                //If the last loop of "foreach" is going on, then only call the function, which will do save.
                if(parentIndex > req.body.materias.length)
                {
                      saveSemester(); // call some function
                }
            }
        });
    });
}

});

The function goes here.

function saveSemester()
{
    // do stuff to save semester
}

The empty array, saved, because before you are trying to save semester, there is no data in that array. So you need to wait for the push to be done and then proceed to do save, which will save the data you want.

UPDATE

Updated my answer. Function will be called once the last loop is going on of foreach. This is what I could think of right now.

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM