survey.db.ts 2.1 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
2
import { HydratedDocument } from "mongoose";
import { Survey, ISurvey, Question, IQuestion } from "../models";
Jiwon Yoon's avatar
Jiwon Yoon committed
3

Jiwon Yoon's avatar
Jiwon Yoon committed
4
5
6
7
8
9
10
11
12
13
export const findUserBySurveyId = async (surveyId: string) => {
  const survey = await Survey.findById(surveyId).populate("user");
  console.log(survey);
  if (survey !== null) {
    console.log(survey.user);
    return survey.user;
  }
  return null;
};

Yoon, Daeki's avatar
Yoon, Daeki committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
export const createSurvey = async (surveyData: ISurvey) => {
  const { _id, questions, ...rest } = surveyData;
  console.log("questions in survey db:", questions, "rest:", rest);
  let newQuestions;
  // questions 있으면 먼저 저장
  if (questions && questions.length > 0) {
    newQuestions = await Promise.all(
      questions.map(async (question) => {
        const { _id, ...questionsWithoutId } = question;
        return await Question.create(questionsWithoutId);
      })
    );
  }
  const survey = new Survey({
    ...rest,
    questions: newQuestions,
  });
  const newSurvey = await (await survey.save()).populate("questions");
Jiwon Yoon's avatar
Jiwon Yoon committed
32
33
  return newSurvey;
};
Jiwon Yoon's avatar
Jiwon Yoon committed
34
35
36
37
38
39

export const getSurveyById = async (surveyId: string) => {
  console.log("survey id", surveyId);
  const survey = await Survey.findById(surveyId).populate("questions");
  return survey;
};
40
41

export const getSurveys = async (userId: string) => {
Yoon, Daeki's avatar
Yoon, Daeki committed
42
43
44
  const surveys = await Survey.find({ user: userId })
    .sort({ updatedAt: -1 })
    .populate("questions");
45
46
  return surveys;
};
Jiwon Yoon's avatar
Jiwon Yoon committed
47

Yoon, Daeki's avatar
Yoon, Daeki committed
48
export const updateSurvey = async (survey: HydratedDocument<ISurvey>) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
49
50
51
  const newSurvey = await Survey.findOneAndUpdate({ _id: survey._id }, survey);
  return newSurvey;
};
52
53
54
55
56
57

export const deleteSurvey = async (surveyId: string) => {
  console.log("survey id", surveyId);
  const survey = await Survey.findOneAndDelete({ _id: surveyId });
  return survey;
};
Jiwon Yoon's avatar
Jiwon Yoon committed
58
59
60
61
62
63
64
65
66
67
68
69
70

export const putNewQuestion = async (newQuestion: any, surveyId: string) => {
  console.log(newQuestion, surveyId);
  if (newQuestion !== null) {
    const updatedSurvey = await Survey.findOneAndUpdate(
      { _id: surveyId },
      { $push: { questions: newQuestion } },
      { new: true }
    ).populate("questions");
    return updatedSurvey;
  }
  return null;
};