node.js - 使用 Mongoose/MongoDB 构建我的模型

标签 node.js mongodb database-design mongoose

我最近开始深入研究服务器端的事物,并且正在开发一个应用程序,我需要在其中考虑如何规划我的模型。

我的用户是教师,并且可以在仪表板中创建学生列表。我的架构将包含更多指令以防止创建重复项,但我在这里简化了它们。这是我到目前为止所做的尝试:

// 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
   }
})

这就是我对后端工作缺乏经验的地方。这个设置对我来说确实没有意义。假设当我去保存一个学生时,它会在数据库中的学生集合下创建一个新学生。这并不理想,因为学生应该以创建它的老师可以严格访问的方式存储。

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

正确地计划这一点绝对很重要,因为老师将来会有更多的能力,例如创建作业、给学生评分等。我想在设计时考虑到最佳实践,以确保教师数据对于其他用户来说是安全的。

最佳答案

我不同意@Lazyexpert。 MongoDB 是一个非关系型数据库 每个文档最多可以存储 16Mb 的数据。确实足够满足你的需要了

The maximum BSON document size is 16 megabytes. The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth. To store documents larger than the maximum size, MongoDB provides the GridFS API.

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

所以我建议你直接在你的老师中添加每个学生的数据。

您可以在这里找到一些提示: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

祝你好运:)

关于node.js - 使用 Mongoose/MongoDB 构建我的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45057602/

相关文章:

Node.js console.log() 没有记录任何东西

javascript - 如何使用nodejs从mongodb获取数据并显示为d3图表

node.js - Mongoose 更新推送到数组的开头

javascript - 用于查找对象类型的 Mongodb 查询

sql-server - 是否有永远不会使用的主键列的原因?

php - 存储不同类型的产品数据的正确方法是什么

node.js - 无法安装 better-sqlite3

node.js - 请求调用在 NodeJs/ExpressJs 中如何工作?

python - 如何使用 PyMongo 在重复键错误后继续插入

PHP:星级评定系统的概念?