question.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { ObjectId } = require('mongoose').Types;
  7. // 问题
  8. class QuestionService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'question');
  11. this.model = this.ctx.model.Question;
  12. this.questionnaire = this.ctx.model.Questionnaire;
  13. }
  14. /**
  15. * 重写删除函数:因为删除题目同时也需要删除问卷保存该题目的id
  16. * @param {Object} { id } 数据id
  17. */
  18. async delete({ id }) {
  19. const res = await this.questionnaire.find({ questions: id }, '+questions');
  20. if (res.length > 0) {
  21. for (const i of res) {
  22. i.questions = i.questions.filter(f => f !== id);
  23. await i.save();
  24. }
  25. }
  26. await this.model.deleteOne({ _id: id });
  27. }
  28. async getQuestions(ids) {
  29. const res = await this.model.find({ _id: ids });
  30. // 按选择顺序排序
  31. const arr = [];
  32. for (let i = 0; i < ids.length; i++) {
  33. const id = ids[i];
  34. const r = res.find(f => ObjectId(id).equals(f._id));
  35. if (r) arr.push(r);
  36. }
  37. return arr;
  38. }
  39. }
  40. module.exports = QuestionService;