Coder1000
Coder1000

Reputation: 4461

How to implement a hit counter in MEAN stack?

QUESTION:

How can I implement a hit count on each post a user makes ?

The count should increase for each unique visitor that views the page.

I know how to increase the count and save it server side, but how can I limit it by IP and prevent manipulation ?

P.S.: I would prefer not to use GA (Google Analytics) for this.


REFERENCE:

This mentions using the cache. Could someone explain how this would look in javascript ?

Page View Counter like on StackOverFlow

Upvotes: 1

Views: 2309

Answers (1)

R. Gulbrandsen
R. Gulbrandsen

Reputation: 3778

One options is to create a document for the id of the post and the IP of the user, to ensure unique visitors. This could look like this:

var hitSchema = mongoose.Schema({
  postId: STRING,
  ip: STRING
});

After a few entries this document would look like this:

[{
  postId: 1,
  ip: 192.168.0.1
}, {
  postId: 1,
  ip: 192.168.0.2
}]

Now, when you do a get request for a post, check if the IP has been logged for the post and and add it if it has'nt.

app.get('/api/posts/:id', function(req, res) {
  var postId = req.params.id;
  var ip = req.connection.remoteAddress;

  Hit.find({postId: postId, ip: ip}).then(function(result) {
    //var newVisitor = false;
    if (!result) { /* add a new record and newVisitor = true */

    return Post.find({id: postId}).then(function(post) {
      //if (newVisitor) { /* update the counter on the post */
      res.send(post);
    });
  });
});

Now, what we have accomplished now is a unique value for all the visitors. You can then either query the document and get a list of IP that has visited to get the count, or add a counter on the Post object with the new IP, and then increment this if it's not found.

The last options is normal when you need to increase the efficiency for the algorithm.

Upvotes: 4

Related Questions