How to append/add objects to a specific object in a JSON object with NODEJS and FileStream

I have a db.json file with two objects:

  • MEMBERS
  • TEAMS

Here's the object...

{
"members": [
    {
        "id": 1,
        "firstName": "John",
        "lastName": "Doe",
        "jobTitle": "Driver",
        "team": "Formula 1 - Car 77",
        "status": "Active"
    },
    {
        "id": 2,
        "firstName": "Alex",
        "lastName": "Sainz",
        "jobTitle": "Driver",
        "team": "Formula 1 - Car 78",
        "status": "Active"
    },
    {
        "id": 3,
        "firstName": "Jeb",
        "lastName": "Jackson",
        "jobTitle": "Reserve Driver",
        "team": "Formula 1 - Car 77",
        "status": "Inactive"
    }
],
"teams": [
    {
        "id": 1,
        "teamName": "Formula 1 - Car 77"
    },
    {
        "id": 2,
        "teamName": "Formula 1 - Car 8"
    },
    {
        "id": 3,
        "teamName": "Formula 2 - Car 54"
    },
  ]
}

I will be adding a NEW member and I want to TARGET that object.

Here's my NODE JS CODE

// Submit Form!
    app.post('/api/addMember', (req, res) => {

        var isWriteable = 'is writable';
        var isNotWriteable = 'is not writable';

        console.log('REQ BODY: ', req.body);

        request('http://localhost:3000/addMember', (err, response, body) => {
            if (response.statusCode <= 500) {
                res.send(body);
                // console.log('RESPONSE!: ', response);
                // console.log('All Members BODY!: ', body);
                // console.log('REQ!: ', req);
                // Now can we Write to the file
                fs.access(dbFile, fs.constants.W_OK, (err) => {
                    console.log(`${dbFile} ${err ? isNotWriteable : isWriteable}`);

                    if (!err) {
                        fs.open(dbFile, 'wx', (err, fd) => {
                            if (err) {
                                if (err.code === 'EEXIST') {
                                    console.error('DB JSON already exists');


                                    dbFileNewMembers.push(dbFileMembers);
                                    dbFileNewTeams.push(dbFileTeams);

                                    console.log('DB FILE NEW JSON MEMBERS:', dbFileNewMembers);
                                    console.log('DB FILE NEW JSON TEAMS:', dbFileNewTeams);

//                                    saveNewMember(req.body)
//                                            .then(result => {
//
//                                                dbFileNewJSON.push(dbFileNewMembers);
//                                                dbFileNewJSON.push(dbFileNewTeams);
//
//                                                console.log('DB FILE NEW JSON:', dbFileNewJSON);
//
//                                                console.log('RESULT OF SAVE NEW MEMBER: ', result);
//                                            });



//                                    fs.appendFile(dbFile, JSON.stringify(req.body), 'utf8', (err) => {
//                                        if (err) {
//                                            console.log('ERROR in saving a member: BODY: ', err);
//                                        } else {
//
//                                            console.log('SUCCESS saving new member!', req.body);
//                                        }
//                                    });

                                    return;
                                }
                                throw err;
                            }
                        });
                    }
                });

            } else {
                console.log('ERROR! DAMN! We blew it!', err);
            }
        });
    });

I tried both functions in the commented out section.

What I get is, the new TEAM member is added at the "end" of the Object NOT at the end of the TEAMS object.

That's all I'm trying.

I did look at:

append json objects to file with nodejs

and

Add JSON objects to JSON object

but they don't address my issue.

I know I need to use appendFile() which is not an issue but I need to append to a specific object INSIDE the main JSON, in this case, TEAMS and in future cases, the team member may need to be UPDATED hence, updating the specific team member.

Thanks for any help.



Read more here: https://stackoverflow.com/questions/64899234/how-to-append-add-objects-to-a-specific-object-in-a-json-object-with-nodejs-and

Content Attribution

This content was originally published by Peter The Angular Dude at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: