answer.db.ts 1.73 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import { Answer, IAnswer } from "../models";
Jiwon Yoon's avatar
Jiwon Yoon committed
2
import { model, Schema, Types } from "mongoose";
Jiwon Yoon's avatar
Jiwon Yoon committed
3
4
5
6
7

export const createAnswer = async (answer: IAnswer) => {
  const newQuestion = await Answer.create(answer);
  return newQuestion;
};
Jiwon Yoon's avatar
Jiwon Yoon committed
8
9

export const getAnswers = async (surveyId: string) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
10
11
  const result = await Answer.aggregate([
    // surveyId에 해당하는 답변들 find
Jiwon Yoon's avatar
Jiwon Yoon committed
12
    { $match: { surveyId: new Types.ObjectId(surveyId) } },
Jiwon Yoon's avatar
Jiwon Yoon committed
13
14
15

    // 같은 question에 대한 답변들을 answers[]에 push
    // {surveyId,questionId,guestId,content} => {_id:questionId, surveyId, answers:[content,content]}
Jiwon Yoon's avatar
Jiwon Yoon committed
16
    {
Jiwon Yoon's avatar
Jiwon Yoon committed
17
18
      $group: {
        _id: "$questionId",
Jiwon Yoon's avatar
Jiwon Yoon committed
19
        surveyId: { $first: "$surveyId" },
20
        answers: { $push: "$content" },
Jiwon Yoon's avatar
Jiwon Yoon committed
21
22
      },
    },
Jiwon Yoon's avatar
Jiwon Yoon committed
23
24

    // question DB popluate
Jiwon Yoon's avatar
Jiwon Yoon committed
25
    {
Jiwon Yoon's avatar
Jiwon Yoon committed
26
      $lookup: {
Jiwon Yoon's avatar
Jiwon Yoon committed
27
28
        from: "questions",
        localField: "_id",
Jiwon Yoon's avatar
Jiwon Yoon committed
29
        foreignField: "_id",
Jiwon Yoon's avatar
Jiwon Yoon committed
30
31
32
33
34
35
36
        as: "questionInfo",
      },
    },
    {
      $unwind: "$questionInfo",
    },

Jiwon Yoon's avatar
Jiwon Yoon committed
37
38
39
    { $set: { "questionInfo.answers": "$answers" } },
    { $unset: "answers" },

Jiwon Yoon's avatar
Jiwon Yoon committed
40
41
42
43
44
45
46
47
    // 질문 순서대로 정렬
    { $sort: { "questionInfo.order": 1 } },

    // surveyId로 묶고 questions 내에 { questionInfo, answers }[]
    {
      $group: {
        _id: "$surveyId",
        questions: {
Jiwon Yoon's avatar
Jiwon Yoon committed
48
          $push: "$questionInfo",
Jiwon Yoon's avatar
Jiwon Yoon committed
49
        },
Jiwon Yoon's avatar
Jiwon Yoon committed
50
51
      },
    },
Jiwon Yoon's avatar
Jiwon Yoon committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

    // survey DB populate
    {
      $lookup: {
        from: "surveys",
        localField: "_id",
        foreignField: "_id",
        as: "survey",
      },
    },
    {
      $unwind: "$survey",
    },

    //밖에 있던 questions를 survey 내부로 이동시키고 survey를 가장 root로 변경
    { $set: { "survey.questions": "$questions" } },
    { $replaceRoot: { newRoot: "$survey" } },
Jiwon Yoon's avatar
Jiwon Yoon committed
69
  ]);
Jiwon Yoon's avatar
Jiwon Yoon committed
70
  return result[0];
Jiwon Yoon's avatar
Jiwon Yoon committed
71
};