I have a front-end application that sends a formData which contains arrays, so I'm using "object-to-formdata" to parse an the following object:
{
"profileImage": {
"name": "5574c060-853b-4999-ba39-1c66d5329704",
"size": 364985,
"mimetype": "image/png",
"url": "uploads/5574c060-853b-4999-ba39-1c66d5329704"
},
"skills": [],
"lessonsFinished": [],
"classes": [],
"_id": "5e3c2f8c80776b12cc336fdf",
"email": "test@test.com",
"password": "$2b$10$iZ3/BuklZ1FCGlyQDPUyMOhcWAfei5yl.llYScbWIv12XWcsokrgS",
"username": "adrian",
"verified": false,
"status": "student",
"color": "blue",
"verificationCode": "50SZWPCHDL685C",
"__v": 0,
"lastName": "Test",
"name": "Test",
}
The object contains objects and arrays, and when parsed and sent to the backend, which uses express, with bodyParser and "express-fileupload" as a file manager, I receive this object:
{
'profileImage[name]': '5574c060-853b-4999-ba39-1c66d5329704',
'profileImage[size]': '364985',
'profileImage[mimetype]': 'image/png',
'profileImage[url]': 'uploads/5574c060-853b-4999-ba39-1c66d5329704',
'skills[]': '',
'lessonsFinished[]': '',
'classes[]': '',
_id: '5e3c2f8c80776b12cc336fdf',
email: 'test@test.com',
password: '$2b$10$iZ3/BuklZ1FCGlyQDPUyMOhcWAfei5yl.llYScbWIv12XWcsokrgS',
username: 'adrian',
verified: 'false',
status: 'student',
color: 'blue',
verificationCode: '50SZWPCHDL685C',
__v: '0',
lastName: 'Test',
name: 'Test',
}
I cannot seem to find a way of parsing this into a normal Object, since I need to use the full object as a query parameter for mongoose.
My Express configuration goes as follows:
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
const express = require('express');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(fileUpload())
Finally, I have the endpoint in which I am receiving the formData:
exports.create = function (model) {
return async function (req, res, next) {
try {
let document = req.body;
if (req.files) {
Object.keys(req.files).forEach(key => {
let file = req.files[key]
file.mv(upload_dir + file.name, (err) => {
if (err) return res.status(500).send(err);
});
document[key] = {
name: file.name,
size: file.size,
mimetype: file.mimetype,
url: upload_dir + file.name
}
})
}
const newDocument = await new model(req.body).save();
res.status(200).send(newDocument);
} catch (err) {
return next({
status: 500,
message: err.message
})
}
}
}
I receive the file just fine, and the rest of the data as well, but i cannot find a way of parsing the "encoded" (as in surrounded by brackets) object keys. I tried building a recursive function to decode them but after several hours I couldn't find a solution and I figured there must be another way already working.
I tried the solutions presented in this thread: How to convert FormData(HTML5 Object) to JSON but those just create an Object with the brackets included in the key...
Thank you in advance for the help!