Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Number Increasing in Database but not Webpage The number of clicks will increase

ID: 3875197 • Letter: N

Question

Number Increasing in Database but not Webpage

The number of clicks will increase in the mongo database when I run this code but it won't increase the counter on the actual webpage. Does anybody have any solutions to what the problem may be with this code? Thanks for any help that may be provided.

HERES MY CODE:

The number of clicks will increase in the mongo database when I run this code but it won't increase the counter on the actual webpage. Does anybody have any solutions to what the problem may be with this code? Thanks for any help that may be provided.

HERES MY CODE:

  console.log('Server-side code running');    const express = require('express');  const MongoClient = require('mongodb').MongoClient;    const app = express();      app.use(express.static('public'));      let db;      const url = 'mongodb://localhost:27017/clicks';    MongoClient.connect(url, (err, database) => {    if (err) {      return console.log(err);    }    db = database;    // start the express web server listening on 8080    app.listen(8080, () => {      console.log('listening on 8080');    });  });      app.get('/', (req, res) => {    res.sendFile(__dirname + '/index.html');  });      app.post('/clicked', (req, res) => {    db.collection('clicks').findOneAndUpdate({}, {$inc: {click : 1}}, (err, result) => {    if(err) throw err;    res.send(result);   });  });      //console.log(click);    //console.log(db);    //   db.collection('clicks').save(click, (err, result) => {  //     if (err) {  //       return console.log(err);  //     }  //     console.log('click added to db');  //     res.sendStatus(201);  //   });  // });      app.get('/clicks', (req, res) => {    db.collection('clicks').find().count((err, result) => {      if (err) return console.log(err);      res.end(result + '');    });  });  

Explanation / Answer

Since you have not provided the client-side script, I am going to assume that you have written the correct client-side scripts using suitable framework.

Lets look how each of your functionality should look like.

MongoClient.connect(url, (err, database) => {

if(err) {

return console.log(err);

2. Data Storage: Correct implementation.

3. Fetch data from db: Please replace your code with the below function and see whether it works or not. You need to replace res.end(result + '') with result.send(result+'').

Or, you can use toArray() function to fetch the data (see below how).