'use strict'; const { CrudService } = require('naf-framework-mongoose/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const assert = require('assert'); const { ObjectId } = require('mongoose').Types; // 问题 class QuestionService extends CrudService { constructor(ctx) { super(ctx, 'question'); this.model = this.ctx.model.Question; this.questionnaire = this.ctx.model.Questionnaire; } /** * 重写删除函数:因为删除题目同时也需要删除问卷保存该题目的id * @param {Object} { id } 数据id */ async delete({ id }) { const res = await this.questionnaire.find({ questions: id }, '+questions'); if (res.length > 0) { for (const i of res) { i.questions = i.questions.filter(f => f !== id); await i.save(); } } await this.model.deleteOne({ _id: id }); } async getQuestions(ids) { const res = await this.model.find({ _id: ids }); // 按选择顺序排序 const arr = []; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const r = res.find(f => ObjectId(id).equals(f._id)); if (r) arr.push(r); } return arr; } } module.exports = QuestionService;