Spaces:
Running
Running
| const mongoose = require('mongoose'); | |
| const visitSchema = new mongoose.Schema( | |
| { | |
| // Optional: Track which user visited (if logged in) | |
| user: { | |
| type: mongoose.Schema.ObjectId, | |
| ref: 'User', | |
| default: null, | |
| }, | |
| // IP address for basic tracking | |
| ipAddress: { | |
| type: String, | |
| required: true, | |
| }, | |
| // User agent for device/browser info | |
| userAgent: { | |
| type: String, | |
| default: '', | |
| }, | |
| // Page visited (optional, for more detailed analytics) | |
| page: { | |
| type: String, | |
| default: '/', | |
| }, | |
| // Session identifier to avoid counting multiple page views as separate visits | |
| sessionId: { | |
| type: String, | |
| required: true, | |
| index: true, | |
| }, | |
| // Number of times this session visited on this day | |
| count: { | |
| type: Number, | |
| default: 1, | |
| }, | |
| // The timestamp of the most recent interaction in this session | |
| lastVisitedAt: { | |
| type: Date, | |
| default: Date.now, | |
| }, | |
| }, | |
| { | |
| timestamps: true, // adds createdAt and updatedAt automatically | |
| toJSON: { virtuals: true }, | |
| toObject: { virtuals: true }, | |
| }, | |
| ); | |
| // Virtual field to display user name/id for logged in users, or sessionId for guests | |
| visitSchema.virtual('visitorInfo').get(function () { | |
| if ( | |
| this.user && | |
| typeof this.user === 'object' && | |
| (this.user.name || this.user.email) | |
| ) { | |
| return this.user.name || this.user.email; | |
| } | |
| return this.user ? this.user.toString() : this.sessionId; | |
| }); | |
| // Index for faster queries on date ranges | |
| visitSchema.index({ createdAt: 1 }); | |
| visitSchema.index({ sessionId: 1, createdAt: 1 }); | |
| const Visit = mongoose.model('Visit', visitSchema); | |
| module.exports = Visit; | |