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

153
Visualizações
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 Respostas
Responde à pergunta

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 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