Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!