How to Implement Visitor Counter in Node.js ?
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.
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:
Step 3: Let us start coding the “app.js” file.
- 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.
Step 4: Now run the app
Output: Now load the app in your browser by hitting http://localhost:3000
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.