class.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. class ClassService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'class');
  10. this.model = this.ctx.model.Class;
  11. this.stumodel = this.ctx.model.Student;
  12. }
  13. async divide(data) {
  14. const termid = await data.termid;
  15. const batchid = await data.batchid;
  16. const name = await data.classname;
  17. const number = await data.students.length;
  18. const type = await data.type;
  19. const classdata = { name, batchid, termid, number, type };
  20. // 根据班级名称查询班级是否已存在
  21. const newclass = await this.model.findOne({ name });
  22. // 如果已经存在抛出异常
  23. if (newclass) {
  24. throw new BusinessError(ErrorCode.DATA_EXIST, '班级名称已存在');
  25. }
  26. // 如果班级不存在则创建班级
  27. const newdata = await this.model.create(classdata);
  28. // 查询班级id
  29. const classid = newdata._id;
  30. // 遍历学生id
  31. for (const studentid of data.students) {
  32. // 根据学生id找到学生数据修改其中的class字段
  33. const student = await this.stumodel.findById(studentid);
  34. student.classid = classid;
  35. student.batchid = batchid;
  36. await student.save();
  37. }
  38. }
  39. }
  40. module.exports = ClassService;