From 5b37132a37337c5f77f345fc3a75ced47a06bb04 Mon Sep 17 00:00:00 2001 From: Michelle <mi00354@surrey.ac.uk> Date: Sat, 22 May 2021 11:26:13 +0100 Subject: [PATCH] Made code clearer, added comments, added error handling --- NodeAPI/index.js | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/NodeAPI/index.js b/NodeAPI/index.js index d4433ed..46e57cc 100644 --- a/NodeAPI/index.js +++ b/NodeAPI/index.js @@ -36,14 +36,22 @@ app.post('/predict', (req,res) => { console.log(JSON.parse(body).predictionText) // res.send(JSON.parse(JSON.parse(body).prediction)); //Display the response on the website - //Add to db // Connect to the db MongoClient.connect(url, function(err, db) { - if (err) throw err; - db.collection('Predictions').insertOne({ - Plot: req.body.plot, - Prediction: JSON.parse(body).predictionText - }) + if(err) { return console.dir(err); } + + // Create collection if does not exist + var collection = db.createCollection('Pred_Records'); + + // Get the data to be stored + var plot = req.body.plot; + var prediction = JSON.parse(body).predictionText; + + // Get rcord to be inserted + var rec = {'Plot':plot, 'Prediction': prediction}; + + // Insert the record to the collection, throw error if insert unsuccessful + collection.insert(rec, {w:1}, function(err, result) {}); }); res.render('predictions',{predictions:JSON.parse(JSON.parse(body).predictionText)}) -- GitLab