用Mongoose / MongoDB构build我的模型

最近我已经开始深入到服务器端,并且正在开发一个应用程序,我需要考虑如何规划我的模型。

我的用户是老师,仪表板中将有能力创build学生列表。 我的模式将包含更多的指令,以防止重复创build,但我在这里简化了它们。 以下是我迄今所尝试的:

// Teacher Model const Teacher = new Schema({ fname: String, lname: String, email: String, }) // Student Model const Student = new Schema({ fname: String, lname: String, full: String, uuid: String grades: { classwork: Array, quizzes: Array, tests: Array } }) 

这是我后端工作经验不足的地方。 这个设置对我来说并不合适。 说我去救学生时,会在数据库中的学生collections下创build一个新学生。 这是不理想的,因为学生应该以创build它的老师严格访问的方式进行存储。

我正在考虑在我的教师模式中创build一个名为“学生”(这将是一个数组)的新密钥,每次创build时都会将学生推入其中。

这对我来说是非常重要的,因为老师将来会有更多的能力,比如创build作业,给学生分级等等。我想用最好的实践来devise这个,确保老师的数据是从其他用户安全。

我不同意@Lazyexpert。 MongoDB是一个非关系数据库,每个文档可以存储16Mb的数据。 这对于你所需要的是足够的

最大的BSON文档大小是16兆字节。 最大的文档大小有助于确保单个文档不能使用过多的RAM,或者在传输过程中使用过多的带宽。 为了存储大于最大大小的文档,MongoDB提供了GridFS API。

即: https : //docs.mongodb.com/manual/reference/limits/

所以我build议你直接在你的老师中join每个学生的数据。

你可以在这里find一些提示: https : //www.safaribooksonline.com/library/view/50-tips-and/9781449306779/ch01.html

所以你的模型看起来像这样:

 const Teacher = new Schema({ fname: String, lname: String, email: String, students : [ { fname: String, lname: String, full: String, uuid: String grades: { classwork: Array, quizzes: Array, tests: Array }, }, ], }) 

如果你绝对需要一个集合学生,那么在你的学生模式上的“保存”行动中使用“后”中间件。 像这样的东西:

 StudentSchema.post('save', function(doc) { Teacher.findOneAndUpdate({_id: <your teacher id>}, <your student object>, callback); }); 

即:mongoosejs.com/docs/api.html#schema_Schema-post

祝你好运 :)

在mongo模型中使用嵌套数组并不那么stream畅。 我可以build议考虑这个数组的大小。

如果你的数组有可能增长 – 不要使用它。

我对你的数据库devise的build议很简单。 将teacherId添加到学生模型。 这样,当您需要根据某位老师获取学生名单时 – 您可以轻松地通过teacherId查询。

所以你的学生模式修改将如下所示:

 const Student = new Schema({ teacherId: { type: mongoose.Schema.Types.ObjectId, index: true, required: true }, fname: String, lname: String, full: String, uuid: String grades: { classwork: Array, quizzes: Array, tests: Array } });