answer.db.ts 1.36 KB
Newer Older
1
import { Answer, IAnswer, Survey } 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) => {
10
  const survey = await Survey.findById(surveyId).populate("questions");
Jiwon Yoon's avatar
Jiwon Yoon committed
11
12
  const result = await Answer.aggregate([
    // surveyId에 해당하는 답변들 find
Jiwon Yoon's avatar
Jiwon Yoon committed
13
    { $match: { surveyId: new Types.ObjectId(surveyId) } },
Jiwon Yoon's avatar
Jiwon Yoon committed
14
15
16

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

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

    {
36
37
38
      $replaceRoot: {
        newRoot: {
          $mergeObjects: [{ $arrayElemAt: ["$question", 0] }, "$$ROOT"],
Jiwon Yoon's avatar
Jiwon Yoon committed
39
        },
Jiwon Yoon's avatar
Jiwon Yoon committed
40
41
      },
    },
42
43
44
    { $unset: "question" },
    { $sort: { order: 1 } },
  ]);
Jiwon Yoon's avatar
Jiwon Yoon committed
45

46
  console.log("result:", result);
Jiwon Yoon's avatar
Jiwon Yoon committed
47

48
49
50
51
52
53
  if (survey && result[0]) {
    const Jsurvey = survey.toJSON();
    Jsurvey.questions = result;
    return Jsurvey;
  }
  return survey;
Jiwon Yoon's avatar
Jiwon Yoon committed
54
};