How to Implement Visitor Counter in Node.js ? - GeeksforGeeks

10 Oct, 2021
We are going to implement Visitor Counter using express and mongoose in nodeJS. The benefit of using mongoose for storing the count in the MongoDB database would be that the count would not be lost when we restart the server. Each time when the browser would get that page the count of visitors would increment by one (1). Let us walk through step by step.
Step 1: Create an “app.js” file and initialize your project with npm.
npm init
Step 2: Install express and mongoose using npm
npm install express
npm install mongoose
Express package would help us to create the server and define the routes for GET requests. Mongoose is an Object Data Modelling Library for MongoDB and NodeJS, which would help us to talk with our MongoDB database.
Project Structure: The project structure would look like this: 
Project structure
 
Step 3: Let us start coding the “app.js” file.
First require express and mongooseCreate the connection to the local MongoDB DatabaseDefine the mongoose Schema to store the records. It has two fields one “name” of String data type and the other “count” of Numeric data type.Create the mongoose Model from the SchemaDefine the root GET request and make the app listen to the local port.
First require express and mongoose
Create the connection to the local MongoDB Database
Define the mongoose Schema to store the records. It has two fields one “name” of String data type and the other “count” of Numeric data type.
Create the mongoose Model from the Schema
Define the root GET request and make the app listen to the local port.
The GET request has one special case when the app has been hit for the very first time. For that case, we need to create the default record with the count of visitors equals 1(one). For other times just increment its value by one.
We use the findOne() function of mongoose which takes a parameter as the searching condition. It returns the first record which matches our condition. If no record matches then it returns a null value. Now let’s see the full code of the “app.js” file.
app.js
// Requiring express to handle routingconst express = require('express')  // Creating app const app = express()  // Requiring mongoose to handle mongoDB Databaseconst mongoose = require('mongoose')  // Connecting to local MongoDBmongoose.connect("mongodb://localhost:27017/visitCounterDB", {    useNewUrlParser: true});  // Creating visitor Schema to hold the// count of visitorsconst visitorSchema = new mongoose.Schema({    name: String,    count: Number})  // Creating Visitor Table in visitCounterDBconst Visitor = mongoose.model("Visitor",visitorSchema)  // Get request to app rootapp.get('/', async function(req,res){          // Storing the records from the Visitor table    let visitors = await Visitor.findOne({name: 'localhost'})      // If the app is being visited first    // time, so no records    if(visitors == null) {                  // Creating a new default record        const beginCount = new Visitor({            name : 'localhost',            count : 1        })          // Saving in the database        beginCount.save()          // Sending thee count of visitor to the browser        res.send(`<h2>Counter: `+1+'</h2>')          // Logging when the app is visited first time        console.log("First visitor arrived")    }    else{                  // Incrementing the count of visitor by 1        visitors.count += 1;          // Saving to the database        visitors.save()          // Sending thee count of visitor to the browser        res.send(`<h2>Counter: `+visitors.count+'</h2>')          // Logging the visitor count in the console        console.log("visitor arrived: ",visitors.count)    }})  // Creating server to listen at localhost 3000app.listen(3000,function(req,res){      // Logging when the server has started    console.log("listening to server 3000")})
Step 4: Now run the app
node app.js
Output: Now load the app in your browser by hitting http://localhost:3000
Output Screen
After closing the server and again restarting, when we visit the root page we saw that the count of visitors is preserved and incremented by one. We are logging these all steps into the console also to verify and understand the output.
console
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Difference between npm i and npm ci in Node.js
Mongoose Populate() Method
Roadmap to Become a Web Developer in 2022
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript