survey.model.ts 804 Bytes
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import { model, Schema, Types } from "mongoose";
2
import { Question } from ".";
Jiwon Yoon's avatar
Jiwon Yoon committed
3
4

export interface ISurvey {
Jiwon Yoon's avatar
Jiwon Yoon committed
5
  _id?: Types.ObjectId;
Jiwon Yoon's avatar
Jiwon Yoon committed
6
7
  title?: string;
  comment?: string;
Jiwon Yoon's avatar
Jiwon Yoon committed
8
  user: Types.ObjectId;
Jiwon Yoon's avatar
Jiwon Yoon committed
9
10
11
  questions: Types.ObjectId[];
}

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const schema = new Schema<ISurvey>(
  {
    title: { type: String },
    comment: { type: String },
    user: { type: Schema.Types.ObjectId, ref: "User" },
    questions: [{ type: Schema.Types.ObjectId, ref: "Question" }],
  },
  { timestamps: true }
);

schema.pre(
  "findOneAndDelete",
  { document: false, query: true },
  async function (next) {
    const doc = await this.model.findOne(this.getFilter());
    const questions = doc.questions;
    await Question.deleteMany({ _id: { $in: questions } });
    next();
  }
);
Jiwon Yoon's avatar
Jiwon Yoon committed
32
33

export default model<ISurvey>("Survey", schema);