CONTEXT
I am learning javascript while building a REST API with node.JS and express. Currently I am stuck on trying to read in my array of objects that has an array of objects in it. Below is a small example of what I am reading in.
[
{
"description":"hhhh",
"goal":"yyyy",
"goalDate":"12/5/2019",
"mSubGoalArray":
[
{
"description":"yyyy",
"goal":"ggggg",
"goalDate":"12/4/2019",
"mSubGoalArray":[]
}
]
},
{
"description":"yy",
"goal":"gg",
"goalDate":"12/11/2019",
"mSubGoalArray":
[
]
}
]
WHAT HAVE I TRIED
I have tried setting this -> bodyParser.urlencoded({extended:true}) to true and then just reading in the full string. When I go to display the data that has been read in VIA postman it comes up shows that it has been read and recognized however it cannot be displayed within the console it shows up as undefined.
I have also tried mimicking all the fields that are included in the object and just reading them in one at a time. This compiles however when i go to interact with the API i end up receiving an array saying Cannot access 'goal' before initialization.
goals.js
const express = require('express');
const router = express.Router();
//getting from the database
router.get('/', (req, res, next) => {
});
//posting to the database
router.post('/', (req, res, next) => {
const Array = req.body.data;
console.log(Array);
/*const goal = [
goal.description = req.body.description,
goal.goal = req.body.goal,
goal.goalDate = req.body.description,
goal.mSubGoalArray = [
mSubGoalArray.description = req.body.description,
mSubGoalArray.goal = req.body.goal,
mSubGoalArray.goalDate = req.body.description,
mSubGoalArray.mSubGoalArray['null'],
]
];*/
res.status(200).json({
the: 'Updated goal'
});
});
module.exports = router;
app.js
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
const goalsRoutes = require('./api/routes/goals');
const loginRoutes = require('./api/routes/login');
app.use('/goals', goalsRoutes);
app.use('/login', loginRoutes);
module.exports = app;
QUESTION#
I know that bodyparser is supposed to allow for inner objects. How can I either display the read in JSON object so that I can confirm that I have successfully transfered the object? How can I get rid of the error goal initilization error doing it the other way.
[mSubGoalArray.description = ..., ...]supposed to do?const Array. Shadowing a native object is asking for trouble.