I'm using ExpressJs and MongoDB. I want to show how many not authorized unique users have opened specific event page.
How should I implement this request counter ?
Check IP address or add some mark in cookie...
You could use a cookie and do something like this:
app.use(express.cookieParser());
app.use(function(req, res, next) {
req.cookies['track_id'] ||= require('connect').utils.uid(32);
next();
});
Now you could on every site just push the id of the cookie:
app.use(function(req, res, next) {
if(!req.isAuthenticated()){
statistics.findAndModify(
{_id: req.url},
{},
{$addToSet: {ids: req.cookies['track_id']}},
{upsert:true}
);
}
next();
});
Then you can query in your mongodb database. If you indexed the ids
field you can query for one id and see which urls they visited, too. The number of visitors is the length of the array.
If you replace $addToSet
with $push
you will also track people on the site twice.
Of course, that all falls apart when people delete their cookies ^^
Note that this is untested and I just write it up as I went along. I also assumed you used the plain node-mongodb-native
, DB query may vary for you. Redis would also be a good solution for this.