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

147
Vistas
Saving data to Mongodb mapping out array automatically

I have been storing data into my mongodb collections for a while now with something like the below:

    const addDoc = {
        email: req.body.email,
        name: req.body.name, 
        region: req.body.region, 
        field1: req.body.accountData.field1,
        field2: req.body.accountData.field2,
        field3: req.body.accountData.field3,
        field4: req.body.accountData.field4,
        field5: req.body.accountData.field5,
   }

I have change the names "field1-5" just for ease of example but they all come from an array in accountData the JSON looks like the below:

{
    email: "email@email.com",
    name: "first name",
    region: "Europe",
    accountData:{
       field1: "field1",
       field2: "field2",
       field3: "field3",
       field4: "field4",
       field5: "field5",
    }
}

I was curious of what you would do if the array in accoundData had hundreds or thousands of fields, is there a way to save each field automatically to mongodb using the field name as the name in the database? This would be so you wouldnt have to manually map out:

field1: req.body.accountData.field1

thousands of times.

Thanks in advance.

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You just want to use desctructuring assignment

const req = {
  body: {
    email: 'aaa@aaa.aa',
    name: 'test',
    region: 'arct',
    accountData: {
      field1: 'some data',
      field2: 'some date 2',
      field3: 'another data'
    }
  }
}

const addDoc = {
  email: req.body.email,
  name: req.body.name,
  region: req.body.region,
  ...req.body.accountData
}

console.log(addDoc)

almost 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