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.
UPDATE!
KG made a suggestion and I modified it.
Here are the variables:
var dbFileJSON = require('./db.json');
var obj = JSON.stringify(dbFileJSON);
console.log('DBFILE OBJ: ', obj);
console.log('DBFILE MEMBERS OBJ BEFORE PUSH: ', dbFileJSON);
dbFileJSON['members'].push(newMember);
console.log('DBFILE MEMBERS OBJ AFTER PUSH: ', dbFileJSON);
dbFileJSON = JSON.stringify(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL STRINGIFY: ', dbFileJSON);
dbFileJSON = JSON.parse(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL: ', dbFileJSON);
console.log('UPDATED TEAM members: ', dbFileJSON);
The result adds it directly to the BOTTOM of the "MEMBERS" array!
This is where I found an potential answer before I implemented KG's answer.
https://stackoverflow.com/questions/38716025/how-to-replace-old-json-object-with-a-new-one-with-nodejs
Now, the ONLY problem left is: I need to REPLACE db.json, because it's not doing that.
My final question is: How do you replace an ENTIRE JSON file with the contents of a new one because I'm still getting the original. Here's the top part of the server.js file to better help understand where I am.
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const path = require('path');
const request = require('request');
const fs = require("fs");
var hsts = require('hsts');
var xssFilter = require('x-xss-protection');
var nosniff = require('dont-sniff-mimetype');
var dbFileJSON = require('./db.json');
var dbFile = 'db.json';
var dbFileMembers = [];
var dbFileTeams = [];
const app = express();
app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.raw());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);
app.use(helmet({
noCache: false
}));
app.use(hsts({
maxAge: 15552000 // 180 days in seconds
}));
app.get('/api/members', (req, res) => {
request('http://localhost:3000/members', (err, response, body) => {
if (response.statusCode <= 500) {
res.send(body);
dbFileMembers.push(body);
console.log('BODY MEMBERS: ', body);
console.log('BODY MEMBERS DBFILEMEMBERS: ', dbFileMembers);
console.log('DBFILE: ', dbFileJSON);
console.log('SUCCESS! We got the members ', dbFileMembers);
} else {
console.log('ERROR getting MEMBERS: ', err);
}
});
});
// TODO: Dropdown! DONE!
app.get('/api/teams', (req, res) => {
request('http://localhost:3000/teams', (err, response, body) => {
if (response.statusCode <= 500) {
res.send(body);
dbFileTeams.push(body);
console.log('SUCCESS! We got the TEAMS! ', JSON.parse(dbFileTeams));
} else {
console.log('ERROR getting TEAMS: ', err);
}
});
});
Here's my code for adding a new Member
// 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);
fs.access(dbFile, fs.constants.W_OK, (err) => {
console.log(`${dbFile} ${err ? isNotWriteable : isWriteable}`);
if (!err) {
fs.open(dbFile, 'wx', (err, fd) => {
if (err) {
console.log('FD: ', fd);
if (err.code === 'EEXIST') {
console.error('DB JSON already exists');
console.log('DB FILE JSON MEMBERS:', dbFileMembers);
console.log('DB FILE JSON TEAMS:', dbFileTeams);
const newMember = req.body;
var obj = JSON.stringify(dbFileJSON);
console.log('DBFILE OBJ: ', obj);
console.log('DBFILE MEMBERS OBJ BEFORE PUSH: ', dbFileJSON);
dbFileJSON['members'].push(newMember);
console.log('DBFILE MEMBERS OBJ AFTER PUSH: ', dbFileJSON);
dbFileJSON = JSON.stringify(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL STRINGIFY: ', dbFileJSON);
dbFileJSON = JSON.parse(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL: ', dbFileJSON);
console.log('UPDATED TEAM members: ', dbFileJSON);
}
}
});
}
});
} else {
console.log('ERROR! DAMN! We blew it!', err);
}
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/my-app/index.html'));
});
app.listen('8000', () => {
console.log('Vrrroooom Vrrroooom! Server starting!');
});
That's it! Any further comment would be dandy!