answer.db.ts 786 Bytes
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
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

export const getAnswers = async (surveyId: string) => {
  const answers = await Answer.aggregate([
    { $match: { surveyId: new Types.ObjectId(surveyId) } },
    {
      $lookup: {
        from: "questions",
        localField: "questionId",
        foreignField: "_id",
        as: "question",
      },
    },
    { $unwind: "$question" },
    {
      $group: {
        _id: "$questionId",
        answers: { $push: { guestId: "$guestId", answer: "$answer" } },
        question: { $mergeObjects: "$question" },
      },
    },
  ]);
  return answers;
};