My Javascript is interacting with the following 2 JSON files:
readers.json:
[
{
"readerID": 1,
"name": "Maria",
"weeklyReadingGoal": 350,
"totalMinutesRead": 5600,
"bookID": 65
},
{
"readerID": 2,
"name": "Daniel",
"weeklyReadingGoal": 210,
"totalMinutesRead": 3000,
"bookID": 65
}
]
Books.json
[
{
"bookID": 65,
"title": "Goodnight Moon",
"author": "Margaret Wise Brown",
"publicationYear": "1953"
},
{
"bookID": 75,
"title": "Winnie-the-Pooh",
"author": "A. A. Milne",
"publicationYear": "1926"
}
]
At the moment, I am able to DELETE a book from book.json
When I delete a book, & that book's bookID exists in a reader.json object, I want to update that ID to 0.
For example, if I delete a book where bookID = 65, I want to change all the bookID's that are equal to 65 in reader.json to null.
Below is my code, I can provide additional code if required:
Books.js:
var data = getBookData();
var pos = data.map(function (e) {
return e.bookID;
}).indexOf(parseInt(req.params.id, 10));
if (pos > -1) {
data.splice(pos, 1);
} else {
res.sendStatus(404);
}
saveBookData(data);
var readerData = getReaderData();
var bookID = req.params.id;
console.log('BOOK ID - ' + bookID); // prints: BOOK ID - 47
readerData.forEach(function (x) {
if (x.bookID === bookID) {
x.bookID = null;
}
else {
console.log('Deleted book was not associated with any reader');
console.log('BOOK ID in else - ' + x.bookID); // prints: BOOK ID in else - 47
}
});
saveReaderData(readerData);
res.sendStatus(204);
});
function getReaderData() {
var data = fs.readFileSync(readerFile, 'utf8');
return JSON.parse(data);
}
When I run this code, the book is removed from books.json, but the matching bookID's in readers.json are remaining the same.
Also, in the else block above, the matching bookID's are being logged, but for some reason the code is not flowing into the if block.
books.jsabove to show how I'm getting the bookID & deleting it. I then want to loop through readers.json & replace all matching bookID's within that to null