MongoDB(Mongoose)数据库结构题
Posted
技术标签:
【中文标题】MongoDB(Mongoose)数据库结构题【英文标题】:MongoDB (Mongoose) database structure question 【发布时间】:2022-01-11 05:10:05 【问题描述】:我目前正在学习 Mongoose 和 nodeJS。我必须创建一个数据库,其中保存了课程注册和学生每门课程的分数。每个科目还与一位老师相关联。想想数据库的结构。确保您可以争论为什么要通过“嵌入”或“参考”连接数据。还要考虑在哪里使用索引和唯一索引。
我目前的想法:
一个学生有多个课程 一个课程有多个学生 学生在一门课程上获得多个分数 一门课程有一位老师我尝试制作以下猫鼬方案:
学生架构:
const mongoose = require("mongoose");
const studentSchema = new mongoose.Schema(
name:
type: String,
minLength: 3,
trim: true,
lowercase: true,
validate:
validator: (value) => /^[a-z ]+$/.test(value),
message: (props) => `$props.value is not a valid name!`
,
required: [ true, "Name is required" ]
,
id:
type: Number,
index: unique: true ,
min: [ 1, "ID must be greater than 0" ],
required: [ true, "ID is required" ]
,
courses : [ type: mongoose.Schema.Types.ObjectId, ref: "Course" ]
,
collection: "students"
);
module.exports = mongoose.model("Student", studentSchema );
课程架构:
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema(
title:
type: String,
minLength: 3,
trim:true,
lowercase:true,
validate:
validator: (value) => /^[a-z ]+$/.test(value),
message: (props) => `$props.value is not a valid course title`
,
required: [true, "Course title is required"]
,
teacher:
type: String,
minLength: 3,
trim: true,
lowercase: true,
validate:
validator: (value) => /^[a-z ]+$/.test(value),
message: (props) => `$props.value is not a valid teacher name`
,
required: [true, "teacher is required"]
,
student : type: mongoose.Schema.Types.ObjectId, ref: "Student"
,
collection: "courses"
);
module.exports = mongoose.model("Course", courseSchema );
我目前面临的问题:
-
在 StudentSchema 中,我使用的是 Id,因为我想要 1、2、3、4 等而不是从 MongoDB 随机生成的 id。这是正确的做法吗?
如何将分数添加到数据库中以及将其放置在哪里?
【问题讨论】:
【参考方案1】:这真的是见仁见智。
如果您需要每个文档的唯一 ID,您应该让 Mongo 处理它。这是有原因的。
在我看来,您应该在 courses
架构中添加一个 scores
数组。
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema(
title:
type: String,
minLength: 3,
trim:true,
lowercase:true,
validate:
validator: (value) => /^[a-z ]+$/.test(value),
message: (props) => `$props.value is not a valid course title`
,
required: [true, "Course title is required"]
,
teacher:
type: String,
minLength: 3,
trim: true,
lowercase: true,
validate:
validator: (value) => /^[a-z ]+$/.test(value),
message: (props) => `$props.value is not a valid teacher name`
,
required: [true, "teacher is required"]
,
student : type: mongoose.Schema.Types.ObjectId, ref: "Student" ,
scores: [
score: Number, // the grade
assignment_id: mongoose.Schema.Types.ObjectId// the id to the test/quiz/homework/etc.. which was graded
],
// You could also just have an array of numbers (scores)
scores: type: [Number]
,
collection: "courses"
);
module.exports = mongoose.model("Course", courseSchema );
【讨论】:
这是否意味着一门课程只有一个学生?一个课程就不能被多个学生重复使用吗?我觉得我正在为每个学生开设一门新课程。 @JensPanis 是的,你是对的。那是我的错,我只是修改了 scores 属性来显示如何添加它。以上是关于MongoDB(Mongoose)数据库结构题的主要内容,如果未能解决你的问题,请参考以下文章