|
| 1 | +import mongoose, { Schema, model, Document, Types } from "mongoose"; |
| 2 | +import {User} from "../models/user_model"; |
| 3 | + |
| 4 | +import { IParticipant } from "./participant_model"; |
| 5 | + |
| 6 | +export interface IEvent extends Document { |
| 7 | + eventId: string; |
| 8 | + name: string; |
| 9 | + description: string; |
| 10 | + joinCode: string; |
| 11 | + startDate: Date; |
| 12 | + endDate: Date; |
| 13 | + maxParticipant: number; |
| 14 | + participants: mongoose.Types.DocumentArray<IParticipant>; |
| 15 | + currentState: string; |
| 16 | + createdBy: string; |
| 17 | +} |
| 18 | + |
| 19 | +const EventSchema = new Schema<IEvent>( |
| 20 | + { |
| 21 | + eventId: { type: String, required: true, unique: true }, |
| 22 | + name: { type: String, required: true }, |
| 23 | + description: { type: String, required: true }, |
| 24 | + joinCode: { type: String, required: true, unique: true }, |
| 25 | + startDate: { type: Date, required: true }, |
| 26 | + endDate: { type: Date, required: true }, |
| 27 | + maxParticipant: { type: Number, required: true }, |
| 28 | + participants: [{ type: Types.ObjectId, ref: "Participant" }], |
| 29 | + currentState: { type: String, required: true }, |
| 30 | + createdBy: { |
| 31 | + type: String, |
| 32 | + required: true, |
| 33 | + validate: { |
| 34 | + validator: async function (email: string) { |
| 35 | + const user = await User.findOne({ email }); |
| 36 | + return !!user; // true if user exists |
| 37 | + }, |
| 38 | + message: "User with this email does not exist" |
| 39 | + } |
| 40 | + } |
| 41 | + }, |
| 42 | + { |
| 43 | + timestamps: true, |
| 44 | + } |
| 45 | +); |
| 46 | + |
| 47 | +// Optional validation: ensure endDate is after startDate |
| 48 | +EventSchema.pre("save", function (next) { |
| 49 | + if (this.endDate <= this.startDate) { |
| 50 | + next(new Error("endDate must be after startDate")); |
| 51 | + } else { |
| 52 | + next(); |
| 53 | + } |
| 54 | +}); |
| 55 | + |
| 56 | +export const Event = model<IEvent>("Event", EventSchema); |
0 commit comments