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 protected]",
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.
CodePudding user response:
You just want to use desctructuring assignment
const req = {
body: {
email: '[email protected]',
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)