gpt4 book ai didi

javascript - Node JS Visitors Mongoose Schema,按年、月、周、天计算访问量

转载 作者:行者123 更新时间:2023-12-05 05:43:59 24 4
gpt4 key购买 nike

您好,这是一个计算我网站访问者数量的架构,我有多个域。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const VisitorSchema = Schema({
domain: String,
count: Number
});

module.exports = mongoose.model('Visitor', VisitorSchema);

我想在 mongoDB 中保存一段时间内我网站的访问者数量。此时我可以增加“计数”属性,但如果我想按年、月和周进行组织怎么办。

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();
}
}

所以我的问题是:如何在 mongoose 中将年份创建为动态属性?我的想法是从 firstVisitDate 属性开始计数。提前致谢。

{ 
domain: String,
firstVisitDate: Date,
2022: {
today: Number,
week: Number,
month: Number,
year: Number
},
2023: {
today: Number,
week: Number,
month: Number,
year: Number,
}
total: Number
}

最佳答案

您可以使用 node-cron 来自动化作业并在每个午夜重置访客计数器:https://www.npmjs.com/package/node-cron

const nodeCron = require('node-cron');

const cron = {
run: function() {
nodeCron.schedule('* * * * *', () => {
updateVisitorDateCounter();
})
}
};
cron.run(); // run every midnight

updateVisitorDateCounter 函数:

async function updateVisitorDateCounter() {
const date = new Date();

if(date.getHours() + date.getMinutes() != 0) return;// prevent restart 'today' counter if server restarts (only works with same time setted in cron)
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const dayName = days[date.getDay()];
const monthName = months[date.getMonth()];

const domainVisitors = await Visitor.find();

for(let visitor of domainVisitors) {
visitor.today = 0;
const visitorUpdated = await visitor.save();
}

const newWeek = dayName === 'Sunday' ? true : false;
if(newWeek) {
for(let visitor of domainVisitors) {
visitor.week = 0;
const visitorUpdated = await visitor.save();
}
}

const newMonth = date.getDate() === 1 ? true : false; //first day of month
if(newMonth) {
for(let visitor of domainVisitors) {
if(visitor.history.length == 0) {
visitor.history = [{ year: date.getFullYear(), months: [{name: monthName, counter: visitor.month}] }]
} else {
let historyMonths = visitor.history.find(x => x.year === date.getFullYear()).months;
historyMonths.push({name: monthName, counter: visitor.month});
visitor.history = [{ year: date.getFullYear(), months: historyMonths }];
}
visitor.month = 0;
const visitorUpdated = await visitor.save();
}
}

const newYear = date.getMonth() === 0 && date.getDate() === 1 ? true : false;
if(newYear) {
// code here ...
}
}

关于javascript - Node JS Visitors Mongoose Schema,按年、月、周、天计算访问量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71687343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com