Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda