| import { Schema, model, Document, Types } from 'mongoose'; | |
| interface ILocationPoint { | |
| coordinates: [number, number]; // [lng, lat] | |
| timestamp: Date; | |
| } | |
| interface ILocationHistory extends Document { | |
| user: Types.ObjectId; | |
| date: string; // YYYY-MM-DD format | |
| locations: ILocationPoint[]; | |
| lastLocation: { | |
| type: "Point"; | |
| coordinates: [number, number]; | |
| }; | |
| createdAt: Date; | |
| updatedAt: Date; | |
| } | |
| const LocationHistorySchema = new Schema<ILocationHistory>({ | |
| user: { | |
| type: Schema.Types.ObjectId, | |
| ref: "User", | |
| required: true | |
| }, | |
| date: { | |
| type: String, // Store as "2025-11-25" for easy querying | |
| required: true | |
| }, | |
| locations: [{ | |
| coordinates: { | |
| type: [Number], | |
| required: true | |
| }, | |
| timestamp: { | |
| type: Date, | |
| default: Date.now | |
| } | |
| }], | |
| lastLocation: { | |
| type: { | |
| type: String, | |
| enum: ["Point"], | |
| default: "Point" | |
| }, | |
| coordinates: { | |
| type: [Number], | |
| required: true | |
| } | |
| } | |
| }, { timestamps: true }); | |
| // Compound unique index: one document per user per day | |
| LocationHistorySchema.index({ user: 1, date: 1 }, { unique: true }); | |
| // For spatial queries on last known location | |
| LocationHistorySchema.index({ lastLocation: "2dsphere" }); | |
| // For date range queries | |
| LocationHistorySchema.index({ date: 1 }); | |
| export default model<ILocationHistory>("LocationHistory", LocationHistorySchema); |