[英]Mongoose: How to extract arrays in subdocuments to a single array in the parent document
An Express server using Mongoose returns the following JSON from the database in one of its routes:使用 Mongoose 的 Express 服务器在其路由之一中从数据库返回以下 JSON:
{
"gradeLevel": 12,
"classes": [
{
"className": "A",
"students": [
"student1", "student2","student3"
]
},
{
"className": "B",
"students": [
"student4", "student5","student6"
]
},
{
"className": "C",
"students": [
"student7", "student8","student9"
]
}
]
}
In the client, I'd like to be able to for example efficiently check if a student is in any of the class subdocuments in the parent document.在客户端,我希望能够例如有效地检查学生是否在父文档中的任何类子文档中。 The following are the solutions I've conceived, but am not sure which is best practice:以下是我构想的解决方案,但不确定哪个是最佳实践:
students
field as well.当学生被推送到班级子文档时,也将学生推送到父母的students
字段。I was at this problem too.我也遇到了这个问题。 But to tackle this you need a separate collection called allStudents
for example where the schema of it is as follows { nameOfStudent: 'String' className: 'String' }
但是要解决这个问题,您需要一个名为allStudents
的单独集合,例如它的架构如下{ nameOfStudent: 'String' className: 'String' }
then aggregate it accordingly with subdoucment.然后将其与子文档相应地聚合。 So that wherever you push a new student into allStudents
with the className
mentioned it will be pushed to the students subdocument of the respective className.因此,无论您将新学生推入allStudents
并提到className
,它将被推入相应 className 的allStudents
子文档。
Querying with dot notation, like用点符号查询,比如
.find({"classes.students":"student8"})
will check the students
field of each object in the classes
array, returning the documents containing the specific student in any class.将检查classes
数组中每个对象的students
字段,返回包含任何班级中特定学生的文档。
Thank you for the answers given.感谢您提供的答案。 Just sharing another solution using vanilla Javascript that might be of use to those in similar situations:只是使用 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.