csc309-team58/sports-matcher/server/schemas/matchModel.js

40 lines
1.5 KiB
JavaScript

import mongoose from "mongoose";
import ModelNameRegister from "./modelNameRegister.js";
const Types = mongoose.Schema.Types; // Some types require defining from this object.
const matchSchema = new mongoose.Schema({
title: { type: String, required: true, trim: true },
when: { type: Date, required: true },
publicity: { type: Number, required: true, default: 2 },
location: {
type: [Number],
required: true,
validate: {
validator: function (v) {
return v.length === 2;
},
message: "Invalid coordinate format (array not length of 2)."
}
},
creator: { type: Types.ObjectId, ref: ModelNameRegister.User },
participants: { type: [{ type: Types.ObjectId, ref: ModelNameRegister.User }], required: true, default: [] },
difficulty: { type: Number, required: true },
sport: { type: Types.ObjectId, ref: ModelNameRegister.Sport },
createDate: { type: Date, required: true, default: Date.now }
});
matchSchema.pre("remove", function (next) {
const match = this;
match.populate("creator").populate("participants");
match.participants.forEach(participant => {
const index = participant.participatingMatches.indexOf(match._id);
participant.participatingMatches.splice(index, 1);
});
match.creator.createdMatches.splice(match.creator.createdMatches.indexOf(match._id), 1);
next();
});
export default mongoose.model(ModelNameRegister.Match, matchSchema);