因此,我将提供您的方法,并且可能是一种天真的方法,因为我对 MongoDB 中的 refs 还不是很好,但这绝对可能是众多解决方案之一
所以据我了解,我们需要以下内容:
现在让我们构建学生模型:
const studentSchema = mongoose.Schema({
firstName:{type:String , required:true},
lastName:{type:String, required:true},
studentNumber:{type:String, required:true, unique:true},//We definitely need uniquely identify students and with student number we can achieve that
classesEnrolled:{type:Array, required:true}
})
const studentModel = mongoose.model('studentModel', studentSchame);
现在让我们构建类模型:
const classSchema = mongoose.Schema({
educator:{type:String, required:true},//Every class has and educator
module:{type:String, required:true, unique:true},//Every class has a module e.g Mat105 etc depending on how the institution name their modules
studentsEnrolled:{type:Array, default:[]},//Giving this a default and not requiring it cause a module can be instantiated and not having students as yet
attendance:{
date:{type:Date, required:true},
studentsAttended:{type:Array, default:[]},//Catering for the fact that a class when created wont have any attendance has a default of empty array but as classes occur then update in document will be key
}
})
所以现在我们有了想要使用的两种模型,我将在下面给出我将如何处理招生等过程的场景:
案例 1。新生入学:
- 因此,当您有新生注册时,您需要所有强制性身份信息。
- 现在在所有信息中,您需要该学生注册的所有模块
- 一旦您收到了所有模块,我现在要做的就是转到类模型并查询学生提供的所有模块,并通过添加新学生来更新 studentsEnrolled 列表。
- 更新每个模块数组后,我会更新数据库中的文档
案例 2:创建新模块
- 这应该是最简单快捷的。
- 我需要关于模块的所有信息,例如 educator、模块名称 等,知道其余部分将具有默认值
- 但是,您不要直截了当地添加一个新模块,您要验证它是否不存在,如果存在则向客户端返回 404
案例3:获取模块注册的学生人数
- 这也应该很容易
- 首先,您要查询要获取信息的模块
- 然后,一旦你有了,假设你将文档存储在变量 module 中
- 然后你意识到我确信你现在可以访问 module.studentEnrolled 这是一个数组
- 现在您可以返回到客户端 module.studentEnrolled.length,这将为您提供已注册的学生人数。
案例 4:考勤
- 现在假设您的网络/移动应用有一个仪表板,其中有学生列表
- 在每个学生的姓名旁边都有一个按钮,上面写着参加和缺席
- 所以我在写作时考虑的解决方案是,在您的客户端中,当您点击 Attended 或 Absent 时,您转发的同时也会使用 JavaScript 日期模块发送当前日期
- 所以现在在您的后端您将收到学号和当前日期以及模块名称
- 然后您如何继续查询要更新考勤登记的模块。假设它保存在变量 module 中
- 现在您要做的是按收到的日期过滤 module.attendance,将该数组保存在 todaysAttendance
- 验证 todayAttendance 是否确实在回馈,如果没有则返回数组,然后您想开始当天的新寄存器 然后保存在 db 中并完成操作
- 否则,如果您返回一个数组,那么您所做的就是将您在后端收到的学号添加到数组中
- 那么最后你想要做的是你想通过 todaysAttendance 列表映射找到当前日期数组并将其替换为新的更新数组,然后获取变量 module 现在已更新然后更新mongoDB 中的模块和内存中的新模块,然后你就完成了