Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

252
Visualizações
mongoose - trying to save an array of documents, only empty array saved

I have a schema defined like this

var PersonelModelSchema = new Schema({
  emailAddress: String,
  fullName: String
});

var ModuleModelSchema = new Schema({
  modName: String,
  personels:[PersonelModelSchema ]
});


var ModulesModelSchema=new Schema({
  modules: [ModuleModelSchema ]
});

var ModulesModel = mongoose.model('ModulesModel ', ModulesModelSchema );

This schema is used to save data sent by another app to an api end point built on nodejs

The json data contains an array, the contents of which I want to save as separate documents - ie is the array has 2 objects, each needs to be saved as separate documents. This is the reason I am using array if ModuleModelSchema, so that I can get all the objects in array.

The data that is posted is looks like this

{"modfulldata" :[{
  "modName": "example-45435q5",
  personels: [
    {
      "emailAddress": "name@example",
      "fullName": "name"
    },
    {
      "emailAddress": "name2@example",
      "fullName": "name2"
    }
  ]
},
{
  "modName": "example-f45b",
  personels: [
    {
      "emailAddress": "name3@example",
      "fullName": "name3"
    },
    {
      "emailAddress": "name4@example",
      "fullName": "name4"
    }
  
  ]
}
]}

And this is the code I am using to save

app.post('/savemd', 
    function(req,res){
        console.log(req.body.modfulldata);// the data is shown correctly here

        mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true });
        var db = mongoose.connection;
        db.on('error', console.error.bind(console, 'connection error:'));
        db.once('open', function callback () {
            console.log("open");          

        });

        var newmods=new ModulesModel (req.body.modfulldata);
        
    ModulesModel.insertMany(newmods).then(function(){
                db.close();
        });

    });

There are no errors thrown. With the console.log statement, i can see the request json data is read correctly. However in mongodb, there is only an empty array in the saved document

mongodb result

What am I doing wrong?

How to save the data correctly?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The issue here is the body.modfulldata is an array and you simply can not create mongoose schema object like this, instead iterate the array and generate mongoose schema object and then insert them. Example:

const newmods = req.body.modfulldata.map(dataObj => {
                  return new ModulesModel(dataObj);
                });
await ModuleModel.insertMany(newmods);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda