survey.db.ts 1.46 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
2
import { Survey, ISurvey } from "../models";

Jiwon Yoon's avatar
Jiwon Yoon committed
3
4
5
6
7
8
9
10
11
12
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;
};

Jiwon Yoon's avatar
Jiwon Yoon committed
13
14
15
16
export const createSurvey = async (survey: ISurvey) => {
  const newSurvey = await Survey.create(survey);
  return newSurvey;
};
Jiwon Yoon's avatar
Jiwon Yoon committed
17
18
19
20
21
22

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

export const getSurveys = async (userId: string) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
25
  const surveys = await Survey.find({ user: userId }).sort({ updatedAt: -1 });
26
27
  return surveys;
};
Jiwon Yoon's avatar
Jiwon Yoon committed
28
29
30
31
32

export const updateSurvey = async (survey: ISurvey) => {
  const newSurvey = await Survey.findOneAndUpdate({ _id: survey._id }, survey);
  return newSurvey;
};
33
34
35
36
37
38

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
39
40
41
42
43
44
45
46
47
48
49
50
51

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;
};