Spaces:
Running
Running
File size: 1,708 Bytes
59c49c1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 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;
|