Skip to content
Related Articles

Related Articles

How to Implement Visitor Counter in Node.js ?

View Discussion
Improve Article
Save Article
  • Last Updated : 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.

  1. First require express and mongoose
  2. Create the connection to the local MongoDB Database
  3. 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.
  4. Create the mongoose Model from the Schema
  5. 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.


// Requiring express to handle routing
const express = require('express')
// Creating app 
const app = express()
// Requiring mongoose to handle mongoDB Database
const mongoose = require('mongoose')
// Connecting to local MongoDB
    useNewUrlParser: true
// Creating visitor Schema to hold the
// count of visitors
const visitorSchema = new mongoose.Schema({
    name: String,
    count: Number
// Creating Visitor Table in visitCounterDB
const Visitor = mongoose.model("Visitor",visitorSchema)
// Get request to app root
app.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
        // 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")
        // Incrementing the count of visitor by 1
        visitors.count += 1;
        // Saving to the database
        // 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 3000
    // 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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!