'use strict'; const assert = require('assert'); const _ = require('lodash'); const { ObjectId } = require('mongoose').Types; const { CrudService } = require('naf-framework-mongoose/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; class ClassService extends CrudService { constructor(ctx) { super(ctx, 'class'); this.model = this.ctx.model.Class; this.stumodel = this.ctx.model.Student; } async divide(data) { const name = await data.classname; const number = await data.students.length; const type = await data.type; const termid = await data.termid; const batchid = await data.batchid; const classdata = { name, batchid, termid, number, type }; // 根据班级名称查询班级是否已存在 const newclass = await this.model.findOne({ name }); // 如果已经存在抛出异常 if (newclass) { throw new BusinessError(ErrorCode.DATA_EXIST, '班级名称已存在'); } // 如果班级不存在则创建班级 const newdata = await this.model.create(classdata); // 查询班级id const classid = newdata._id; // 遍历学生id for (const studentid of data.students) { // 根据学生id找到学生数据修改其中的class字段 const student = await this.stumodel.findById(studentid); student.classid = classid; student.batchid = batchid; student.termid = termid; await student.save(); } } } module.exports = ClassService;