Hi this is a Schema to count the amount of visitors to my sites, i have multiple domains.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const VisitorSchema = Schema({
domain: String,
count: Number
});
module.exports = mongoose.model('Visitor', VisitorSchema);
I would like to save in mongoDB the amount of visitors to my sites in periods of time. At this point i can increase the ‘count’ property but what if i want to organize by years, months and weeks.
async function saveVisitor(domain){
let visitors = await Visitor.findOne({domain});
if(visitors == null) {
const startCount = new Visitor({
domain: domain,
count: 1
});
startCount.save();
} else {
visitors.count++;
visitors.save();
}
}
So my question is: how can i create the years as dynamic properties in mongoose?. What i have in mind is to start counting from a firstVisitDate property. Thanks in advance.
{
domain: String,
firstVisitDate: Date,
2022: {
today: Number,
week: Number,
month: Number,
year: Number
},
2023: {
today: Number,
week: Number,
month: Number,
year: Number,
}
total: Number
}
2
Answers
this way is not good and have some problem like what if you want to add more step organization like visitor of 2 months or something like that.
instead of adding a number into your counter create an array of visits and add timestamp to it each time a user visit your site.
by this way you can easily query visitor for each period time you want also you can create a graph by time of your visitor visit site. you can expand this and by saving timestamp with user id you can know what user what time visit your site or something like that.
You can use node-cron to automatize jobs and reset visitors counter every midnight: https://www.npmjs.com/package/node-cron
updateVisitorDateCounter function: