Mongoose:如何将子文档中的数组提取到父文档中的单个数组
Mongoose: How to extract arrays in subdocuments to a single array in the parent document
使用 Mongoose 的 Express 服务器 returns 以下 JSON 来自其路由之一的数据库:
{
"gradeLevel": 12,
"classes": [
{
"className": "A",
"students": [
"student1", "student2","student3"
]
},
{
"className": "B",
"students": [
"student4", "student5","student6"
]
},
{
"className": "C",
"students": [
"student7", "student8","student9"
]
}
]
}
在客户端中,我希望能够有效地检查学生是否在父文档的 class 子文档的 any 中。以下是我设想的解决方案,但我不确定哪个是最佳实践:
- 当学生被推送到 class 子文档时,也将学生推送到家长的
students
字段。
- 在模型的 toJSON 转换中添加一个新字段以编译所有学生。
- 在客户端中使用 vanilla Javascript 来提取所有学生
我也遇到了这个问题。但是要解决这个问题,您需要一个名为 allStudents
的单独集合,例如它的架构如下
{ nameOfStudent: 'String' className: 'String' }
然后将其与子文件相应地聚合。因此,无论您将提到的 className
的新学生推送到 allStudents
中,它都会被推送到相应 className 的学生子文档中。
用点号查询,喜欢
.find({"classes.students":"student8"})
将检查 classes
数组中每个对象的 students
字段,返回包含任何 class.
中特定学生的文档
感谢您给出的答案。只是分享另一个使用 vanilla Javascript 的解决方案,可能对处于类似情况的人有用:
checkStudent = (batch, student) => {
let result = null
const inClass = (cls) => {
if (cls.students.includes(student)) {
result = cls
return true
}
return false
}
batch.classes.some(inClass)
return result
}
使用 Mongoose 的 Express 服务器 returns 以下 JSON 来自其路由之一的数据库:
{
"gradeLevel": 12,
"classes": [
{
"className": "A",
"students": [
"student1", "student2","student3"
]
},
{
"className": "B",
"students": [
"student4", "student5","student6"
]
},
{
"className": "C",
"students": [
"student7", "student8","student9"
]
}
]
}
在客户端中,我希望能够有效地检查学生是否在父文档的 class 子文档的 any 中。以下是我设想的解决方案,但我不确定哪个是最佳实践:
- 当学生被推送到 class 子文档时,也将学生推送到家长的
students
字段。 - 在模型的 toJSON 转换中添加一个新字段以编译所有学生。
- 在客户端中使用 vanilla Javascript 来提取所有学生
我也遇到了这个问题。但是要解决这个问题,您需要一个名为 allStudents
的单独集合,例如它的架构如下
{ nameOfStudent: 'String' className: 'String' }
然后将其与子文件相应地聚合。因此,无论您将提到的 className
的新学生推送到 allStudents
中,它都会被推送到相应 className 的学生子文档中。
用点号查询,喜欢
.find({"classes.students":"student8"})
将检查 classes
数组中每个对象的 students
字段,返回包含任何 class.
感谢您给出的答案。只是分享另一个使用 vanilla Javascript 的解决方案,可能对处于类似情况的人有用:
checkStudent = (batch, student) => {
let result = null
const inClass = (cls) => {
if (cls.students.includes(student)) {
result = cls
return true
}
return false
}
batch.classes.some(inClass)
return result
}