class.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 name = await data.classname;
  15. const number = await data.students.length;
  16. const type = await data.type;
  17. const termid = await data.termid;
  18. const batchid = await data.batchid;
  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. // const classid = newclass._id;
  26. // const oldstudents = this.stumodel.find({ classid });
  27. // for (const oldstudent of oldstudents) {
  28. // oldstudent.classid = null;
  29. // }
  30. // // 遍历学生id
  31. // for (const studentid of data.students) {
  32. // // 根据学生id找到学生数据修改其中的class字段
  33. // const student = await this.stumodel.findById(studentid);
  34. // student.batchid = batchid;
  35. // student.classid = classid;
  36. // await student.save();
  37. // }
  38. } else {
  39. // 如果班级不存在则创建班级
  40. const newdata = await this.model.create(classdata);
  41. // 查询班级id
  42. const classid = newdata._id;
  43. // 遍历学生id
  44. for (const studentid of data.students) {
  45. // 根据学生id找到学生数据修改其中的class字段
  46. const student = await this.stumodel.findById(studentid);
  47. student.classid = classid;
  48. student.batchid = batchid;
  49. student.termid = termid;
  50. await student.save();
  51. }
  52. }
  53. }
  54. }
  55. module.exports = ClassService;